├── .gitignore ├── go.mod ├── types ├── xml.go ├── watson.go ├── yaml.go ├── json.go ├── msgpack.go ├── toml.go ├── strategy.go └── types.go ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── CHANGELOG.md ├── go.sum ├── LICENSE ├── README.md ├── stres.go └── stres_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | main.go 2 | strings -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Vinetwigs/stres 2 | 3 | go 1.17 4 | 5 | require gopkg.in/yaml.v3 v3.0.1 6 | 7 | require github.com/pelletier/go-toml/v2 v2.0.2 8 | 9 | require ( 10 | github.com/genkami/watson v1.0.0 11 | github.com/vmihailenco/msgpack/v5 v5.2.0 12 | ) 13 | 14 | require github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect 15 | -------------------------------------------------------------------------------- /types/xml.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "encoding/xml" 4 | 5 | type XMLStrategy struct{} 6 | 7 | func (x *XMLStrategy) encode(n *Nesting) ([]byte, error) { 8 | return xml.MarshalIndent(n, "", "\t") 9 | } 10 | 11 | func (x *XMLStrategy) decode(data []byte, v interface{}) error { 12 | if len(data) == 0 { 13 | return nil 14 | } 15 | 16 | return xml.Unmarshal(data, v) 17 | } 18 | -------------------------------------------------------------------------------- /types/watson.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/genkami/watson" 4 | 5 | type WatsonStrategy struct{} 6 | 7 | func (w *WatsonStrategy) encode(n *Nesting) ([]byte, error) { 8 | return watson.Marshal(n) 9 | } 10 | 11 | func (w *WatsonStrategy) decode(data []byte, v interface{}) error { 12 | if len(data) == 0 { 13 | return nil 14 | } 15 | 16 | return watson.Unmarshal(data, v) 17 | } 18 | -------------------------------------------------------------------------------- /types/yaml.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | yaml "gopkg.in/yaml.v3" 5 | ) 6 | 7 | type YAMLStrategy struct{} 8 | 9 | func (y *YAMLStrategy) encode(n *Nesting) ([]byte, error) { 10 | return yaml.Marshal(n) 11 | } 12 | 13 | func (y *YAMLStrategy) decode(data []byte, v interface{}) error { 14 | if len(data) == 0 { 15 | return nil 16 | } 17 | 18 | return yaml.Unmarshal(data, v) 19 | } 20 | -------------------------------------------------------------------------------- /types/json.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | type JSONStrategy struct{} 8 | 9 | func (j *JSONStrategy) encode(n *Nesting) ([]byte, error) { 10 | return json.MarshalIndent(n, "", "\t") 11 | } 12 | 13 | func (j *JSONStrategy) decode(data []byte, v interface{}) error { 14 | if len(data) == 0 { 15 | return nil 16 | } 17 | 18 | return json.Unmarshal(data, v) 19 | } 20 | -------------------------------------------------------------------------------- /types/msgpack.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/vmihailenco/msgpack/v5" 4 | 5 | type MsgPackStrategy struct{} 6 | 7 | func (m *MsgPackStrategy) encode(n *Nesting) ([]byte, error) { 8 | return msgpack.Marshal(n) 9 | } 10 | 11 | func (m *MsgPackStrategy) decode(data []byte, v interface{}) error { 12 | if len(data) == 0 { 13 | return nil 14 | } 15 | 16 | return msgpack.Unmarshal(data, v) 17 | } 18 | -------------------------------------------------------------------------------- /types/toml.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "bytes" 5 | 6 | "github.com/pelletier/go-toml/v2" 7 | ) 8 | 9 | type TOMLStrategy struct{} 10 | 11 | func (t *TOMLStrategy) encode(n *Nesting) ([]byte, error) { 12 | buf := bytes.Buffer{} 13 | enc := toml.NewEncoder(&buf) 14 | enc.SetIndentTables(true) 15 | err := enc.Encode(n) 16 | return buf.Bytes(), err 17 | } 18 | 19 | func (t *TOMLStrategy) decode(data []byte, v interface{}) error { 20 | if len(data) == 0 { 21 | return nil 22 | } 23 | 24 | return toml.Unmarshal(data, v) 25 | } 26 | -------------------------------------------------------------------------------- /types/strategy.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type StrategyAlgo interface { 4 | decode(data []byte, v interface{}) error 5 | encode(n *Nesting) ([]byte, error) 6 | } 7 | 8 | type EncoderDecoder struct { 9 | strategy StrategyAlgo 10 | } 11 | 12 | func (e *EncoderDecoder) SetStrategy(s StrategyAlgo) { 13 | e.strategy = s 14 | } 15 | 16 | func (e *EncoderDecoder) GetStrategy() StrategyAlgo { 17 | return e.strategy 18 | } 19 | 20 | func (e *EncoderDecoder) Encode(n *Nesting) ([]byte, error) { 21 | return e.strategy.encode(n) 22 | } 23 | 24 | func (e *EncoderDecoder) Decode(data []byte, v interface{}) error { 25 | return e.strategy.decode(data, v) 26 | } 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [1.3.0] - 2022-06-14 9 | 10 | ### Added 11 | 12 | - Support for [MessagePack file format](https://msgpack.org/) 13 | 14 | ### Changed 15 | 16 | - LoadValues function now uses goroutines to load values into the internal dictionaries faster 17 | - Reduced GetQuantityString function complexity 18 | 19 | ## [1.2.1] - 2022-06-11 20 | 21 | ### Fixed 22 | 23 | - Fixed pending debug code 24 | 25 | ## [1.2.0] - 2022-06-11 26 | 27 | ### Added 28 | 29 | - Support for [JSON file format](https://www.json.org/json-en.html) 30 | - Support for [YAML file format](https://yaml.org/) 31 | - Support for [TOML file format](https://toml.io/en/) 32 | - Support for [WATSON file format](https://github.com/genkami/watson) 33 | 34 | - SetResourceType function 35 | 36 | - FileType enum 37 | 38 | ### Changed 39 | 40 | - CreateXMLFile function is now CreateResourceFile and takes a FileType parameter 41 | - DeleteResourceFile function is now DeleteResourceFile 42 | - LoadValues function now takes a FileType parameter 43 | 44 | ## [1.1.0] - 2022-06-06 45 | 46 | ### Added 47 | 48 | - Support for XML file format 49 | 50 | - CreateXMLFile, DeleteXMLFile, LoadValues, NewString, NewStringArray, NewQuantityString, SetFewThreshold, GetString, GetStringArray, GetQuantityString functions -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/fxamacker/cbor/v2 v2.2.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo= 4 | github.com/genkami/watson v1.0.0 h1:wnitYUtaR8GWNQhvJ/VCoqOrC12iRRvtWlff9IKVJmI= 5 | github.com/genkami/watson v1.0.0/go.mod h1:h0pRN42xxvCHX/Oyopf4AxtAv4z0+51qRN+K6UxF70g= 6 | github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= 7 | github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 8 | github.com/pelletier/go-toml/v2 v2.0.2 h1:+jQXlF3scKIcSEKkdHzXhCTDLPFi5r1wnK6yPS+49Gw= 9 | github.com/pelletier/go-toml/v2 v2.0.2/go.mod h1:MovirKjgVRESsAvNZlAjtFwV867yGuwRkXbG66OzopI= 10 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 11 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 13 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 14 | github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= 15 | github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= 16 | github.com/vmihailenco/msgpack/v5 v5.2.0 h1:ZhIAtVUP1mme8GIlpiAnmTzjSWMexA/uNF2We85DR0w= 17 | github.com/vmihailenco/msgpack/v5 v5.2.0/go.mod h1:fEM7KuHcnm0GvDCztRpw9hV0PuoO2ciTismP6vjggcM= 18 | github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= 19 | github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= 20 | github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= 21 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 22 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 23 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 24 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 25 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 26 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 27 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 28 | -------------------------------------------------------------------------------- /types/types.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "encoding/xml" 4 | 5 | type FileType string 6 | 7 | type Plural struct { 8 | XMLName xml.Name `xml:"plurals" json:"plurals" yaml:"plurals" toml:"plurals" watson:"plurals" msgpack:"plurals"` 9 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 10 | Items []*PluralItem `xml:"item" json:"items" yaml:"items,flow" toml:"items,multiline" watson:"items" msgpack:"items,as_array"` 11 | } 12 | 13 | type PluralItem struct { 14 | XMLName xml.Name `xml:"item" json:"item" yaml:"item" toml:"item" watson:"item" msgpack:"item"` 15 | Quantity string `xml:"quantity,attr" json:"quantity" yaml:"quantity" toml:"quantity" watson:"quantity" msgpack:"quantity"` 16 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 17 | } 18 | 19 | type Item struct { 20 | XMLName xml.Name `xml:"item" json:"item" yaml:"item" toml:"item" watson:"item" msgpack:"item"` 21 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 22 | } 23 | 24 | type StringArray struct { 25 | XMLName xml.Name `xml:"string-array" json:"string-array" yaml:"string-array" toml:"string-array" watson:"string-array" msgpack:"string-array"` 26 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 27 | Items []*Item `xml:"item" json:"items" yaml:"items,flow" toml:"items,multiline" watson:"items" msgpack:"items,as_array" ` 28 | } 29 | 30 | type String struct { 31 | XMLName xml.Name `xml:"string" json:"string" yaml:"string" toml:"string" watson:"string" msgpack:"string"` 32 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 33 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 34 | } 35 | 36 | type Nesting struct { 37 | XMLName xml.Name `xml:"resources" json:"resources" yaml:"resources" toml:"resources" watson:"resources" msgpack:"resources"` 38 | Strings []*String `xml:"string" json:"string" yaml:"string,flow" toml:"string,multiline" watson:"string" msgpack:"string,as_array"` 39 | StringsArray []*StringArray `xml:"string-array" json:"string-array" yaml:"string-array,flow" toml:"string-array,multiline" watson:"string-array" msgpack:"string-array,as_array"` 40 | Plurals []*Plural `xml:"plurals" json:"plurals" yaml:"plurals,flow" toml:"plurals,multiline" watson:"plurals" msgpack:"plurals,as_array"` 41 | } 42 | -------------------------------------------------------------------------------- /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, 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Go Report Card](https://goreportcard.com/badge/github.com/Vinetwigs/stres)](https://goreportcard.com/report/github.com/Vinetwigs/stres) 2 | ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/Vinetwigs/stres) 3 | ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/Vinetwigs/stres) 4 | ![GitHub last commit](https://img.shields.io/github/last-commit/Vinetwigs/stres) 5 | [![stars - stres](https://img.shields.io/github/stars/Vinetwigs/stres?style=social)](https://github.com/Vinetwigs/stres) 6 | [![forks - stres](https://img.shields.io/github/forks/Vinetwigs/stres?style=social)](https://github.com/Vinetwigs/stres) 7 | [![License](https://img.shields.io/badge/License-Apache_License_2.0-orange)](#license) 8 | [![issues - vilmos](https://img.shields.io/github/issues/Vinetwigs/stres)](https://github.com/Vinetwigs/stres/issues) 9 | 10 |

stres - Android Studio string resources in Go

11 |

12 | 13 | A simple and easy-to-use library to import and export string resources into your Go applications just like you would do in Android Studio. 14 | Useful to separate business logic from UI texts or to handle string translations. 15 | 16 |

17 | 18 | ## Table of contents 19 | 20 | * [References](#references) 21 | * [Prerequisites](#prerequisites) 22 | * [Installing](#installing) 23 | + [Install module](#install-module) 24 | + [Import in your project](#import-in-your-project) 25 | - [Documentation](#documentation) 26 | * [Types](#types) 27 | + [Plural](#plural) 28 | + [PluralItem](#pluralitem) 29 | + [Item](#item) 30 | + [StringArray](#stringarray) 31 | + [String](#string) 32 | + [Nesting](#nesting) 33 | * [CreateResourceFile](#createresourcefile) 34 | * [DeleteResourceFile](#deleteresourcefile) 35 | * [LoadValues](#loadvalues) 36 | * [SetResourceType](#setresourcetype) 37 | * [NewString](#newstring) 38 | * [NewStringArray](#newstringarray) 39 | * [NewQuantityString](#newquantitystring) 40 | * [SetFewThreshold](#setfewthreshold) 41 | * [GetString](#getstring) 42 | * [GetArrayString](#getarraystring) 43 | * [GetQuantityString](#getquantitystring) 44 | - [Contributors](#contributors) 45 | 46 | 47 | ### References 48 | 49 | * [Android Studio string resources](https://developer.android.com/guide/topics/resources/string-resource) 50 | * [CHANGELOG](./CHANGELOG.md) 51 | 52 | [Back to top](#table-of-contents) 53 | 54 | ### Prerequisites 55 | 56 | * Make sure you have at least installed `Go v1.17`. 57 | 58 | [Back to top](#table-of-contents) 59 | 60 | ### Installing 61 | 62 | #### Install module 63 | ``` 64 | go get github.com/Vinetwigs/stres 65 | ``` 66 | 67 | [Back to top](#table-of-contents) 68 | 69 | #### Import in your project 70 | ``` 71 | import("github.com/Vinetwigs/stres") 72 | ``` 73 | [Back to top](#table-of-contents) 74 | 75 | ## Documentation 76 | 77 | ### Types 78 | 79 | #### Plural 80 | 81 | ```go 82 | type Plural struct { 83 | XMLName xml.Name `xml:"plurals" json:"plurals" yaml:"plurals" toml:"plurals" watson:"plurals" msgpack:"plurals"` 84 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 85 | Items []*PluralItem `xml:"item" json:"items" yaml:"items,flow" toml:"items,multiline" watson:"items" msgpack:"items,as_array"` 86 | } 87 | ``` 88 | 89 | [Back to top](#table-of-contents) 90 | 91 | #### PluralItem 92 | 93 | ```go 94 | type PluralItem struct { 95 | XMLName xml.Name `xml:"item" json:"item" yaml:"item" toml:"item" watson:"item" msgpack:"item"` 96 | Quantity string `xml:"quantity,attr" json:"quantity" yaml:"quantity" toml:"quantity" watson:"quantity" msgpack:"quantity"` 97 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 98 | } 99 | ``` 100 | 101 | [Back to top](#table-of-contents) 102 | 103 | #### Item 104 | 105 | ```go 106 | type Item struct { 107 | XMLName xml.Name `xml:"item" json:"item" yaml:"item" toml:"item" watson:"item" msgpack:"item"` 108 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 109 | } 110 | ``` 111 | 112 | [Back to top](#table-of-contents) 113 | 114 | #### StringArray 115 | 116 | ```go 117 | type StringArray struct { 118 | XMLName xml.Name `xml:"string-array" json:"string-array" yaml:"string-array" toml:"string-array" watson:"string-array" msgpack:"string-array"` 119 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 120 | Items []*Item `xml:"item" json:"items" yaml:"items,flow" toml:"items,multiline" watson:"items" msgpack:"items,as_array" ` 121 | } 122 | ``` 123 | 124 | [Back to top](#table-of-contents) 125 | 126 | #### String 127 | 128 | ```go 129 | type String struct { 130 | XMLName xml.Name `xml:"string" json:"string" yaml:"string" toml:"string" watson:"string" msgpack:"string"` 131 | Name string `xml:"name,attr" json:"name" yaml:"name" toml:"name" watson:"name" msgpack:"name"` 132 | Value string `xml:",innerxml" json:"value" yaml:"value" toml:"value" watson:"value" msgpack:"value"` 133 | } 134 | ``` 135 | 136 | [Back to top](#table-of-contents) 137 | 138 | #### Nesting 139 | 140 | ```go 141 | type Nesting struct { 142 | XMLName xml.Name `xml:"resources" json:"resources" yaml:"resources" toml:"resources" watson:"resources" msgpack:"resources"` 143 | Strings []*String `xml:"string" json:"string" yaml:"string,flow" toml:"string,multiline" watson:"string" msgpack:"string,as_array"` 144 | StringsArray []*StringArray `xml:"string-array" json:"string-array" yaml:"string-array,flow" toml:"string-array,multiline" watson:"string-array" msgpack:"string-array,as_array"` 145 | Plurals []*Plural `xml:"plurals" json:"plurals" yaml:"plurals,flow" toml:"plurals,multiline" watson:"plurals" msgpack:"plurals,as_array"` 146 | } 147 | ``` 148 | 149 | [Back to top](#table-of-contents) 150 | 151 | ### CreateResourceFile 152 | *Creates strings resource file in "strings" directory, throws an error otherwise. Takes a FileType parameter to specify strings file format.* 153 | 154 | `file, err := stres.CreateXMLFile()` 155 | 156 | | Parameter | Type | Description | 157 | |-----------|--------|---------------------------------------| 158 | | t | types.FileType | enum value to specify file format | 159 | 160 | [Back to top](#table-of-contents) 161 | 162 | ### DeleteResourceFile 163 | *Deletes resource file if exists, throws an error otherwise. Uses setted resource file extension.* 164 | 165 | `err := stres.DeleteXMLFile()` 166 | 167 | [Back to top](#table-of-contents) 168 | 169 | ### LoadValues 170 | *Loads values from strings file into internal dictionaries. Needs to be invoked only one time (but before getting strings values).Takes a FileType parameter to specify strings file format.* 171 | 172 | `err := stres.LoadValues()` 173 | 174 | [Back to top](#table-of-contents) 175 | 176 | | Parameter | Type | Description | 177 | |-----------|--------|---------------------------------------| 178 | | t | types.FileType | enum value to specify file format | 179 | 180 | ### SetResourceType 181 | *Used to specify string file extension. If t is a wrong FileType, sets resource type to XML by default.* 182 | 183 | `stres.SetResourceType(stres.WATSON)` 184 | 185 | | Parameter | Type | Description | 186 | |-----------|--------|---------------------------------------| 187 | | t | types.FileType | enum value to specify file format | 188 | 189 | [Back to top](#table-of-contents) 190 | 191 | ### NewString 192 | *Adds a new string resource to resource file. Throws an error if the chosen name is already inserted or it is an empty string. Used for programmatic insertion (manual insertion recommended).* 193 | 194 | `String, err := stres.NewString("name", "value")` 195 | 196 | 197 | | Parameter | Type | Description | 198 | |-----------|--------|---------------------------------------| 199 | | name | string | unique name to identify the string | 200 | | value | string | string to associate to the given name | 201 | 202 | Returns String instance and error. 203 | 204 | [Back to top](#table-of-contents) 205 | 206 | ### NewStringArray 207 | *Adds a new string-array resource to resource file. Throws an error if the chosen name is already inserted or it is an empty string. Used for programmatic insertion (manual insertion recommended).* 208 | 209 | `strArr, err := stres.NewStringArray("name", []string{"value1","value2",...})` 210 | 211 | | Parameter | Type | Description | 212 | |-----------|--------|---------------------------------------| 213 | | name | string | unique name to identify the string | 214 | | values | []string | array of strings to associate to the given name | 215 | 216 | Returns StringArray instance and error. 217 | 218 | [Back to top](#table-of-contents) 219 | 220 | ### NewQuantityString 221 | *Adds a new quantity string resource to resource file. Throws an error if the chosen name is already inserted or it is an empty string. The function uses only the first 5 values in the array. The first value is assigned to "zero" quantity. The second value is assigned to "one" quantity. The third value is assigned to "two" quantity. The fourth value is assigned to "few" quantity. The fifth value is assigned to "more" quantity. Used for programmatic insertion (manual insertion recommended).* 222 | 223 | `qntStr, err := stres.NewQuantityString("name", []string{"zero","one", "two", ...})` 224 | 225 | | Parameter | Type | Description | 226 | |-----------|--------|---------------------------------------| 227 | | name | string | unique name to identify the string | 228 | | values | []string | array of strings for quantities to associate to the given name | 229 | 230 | Returns Plural instance and error. 231 | 232 | [Back to top](#table-of-contents) 233 | 234 | ### SetFewThreshold 235 | *Sets the threshold for "few" values in quantity strings.When getting quantity strings values, the function checks if the given count is less OR EQUAL to this value.(default value: 20)* 236 | 237 | `stres.SetFewThreshold(25)` 238 | 239 | | Parameter | Type | Description | 240 | |-----------|--------|---------------------------------------| 241 | | value | int | new value for 'few' threshold | 242 | 243 | Returns Plural instance and error. 244 | 245 | [Back to top](#table-of-contents) 246 | 247 | ### GetString 248 | *Returns the string resource's value with the given name. If not exists, returns empty string.* 249 | 250 | `str := GetString("name")` 251 | 252 | | Parameter | Type | Description | 253 | |-----------|--------|---------------------------------------| 254 | | name | string | unique name given to the corresponding string | 255 | 256 | Returns a string. 257 | 258 | [Back to top](#table-of-contents) 259 | 260 | ### GetArrayString 261 | *Returns the string-array resource's values with the given name. If not exists, returns nil.* 262 | 263 | `strArr := GetStringArray("name")` 264 | 265 | | Parameter | Type | Description | 266 | |-----------|--------|---------------------------------------| 267 | | name | string | unique name given to the corresponding string-array | 268 | 269 | Returns an array of strings. 270 | 271 | [Back to top](#table-of-contents) 272 | 273 | ### GetQuantityString 274 | *Returns the quantity string resource's corresponding string value based on the value of the given count parameter. If the plural is not found, returns an empty string.* 275 | 276 | `strArr := GetQuantityString("name", 10)` 277 | 278 | | Parameter | Type | Description | 279 | |-----------|--------|---------------------------------------| 280 | | name | string | unique name to identify the string | 281 | | count | int | quantity to fetch the corresponding string | 282 | 283 | Returns a string. 284 | 285 | [Back to top](#table-of-contents) 286 | 287 | ## Contributors 288 | 289 | 290 | 291 | 292 | -------------------------------------------------------------------------------- /stres.go: -------------------------------------------------------------------------------- 1 | package stres 2 | 3 | import ( 4 | "errors" 5 | "io/ioutil" 6 | "os" 7 | "strings" 8 | "sync" 9 | 10 | "github.com/Vinetwigs/stres/types" 11 | ) 12 | 13 | var fileType types.FileType 14 | var encDec = types.EncoderDecoder{} 15 | 16 | var quantityValues = [...]string{"zero", "one", "two", "few", "many"} 17 | 18 | var data []byte 19 | var string_entries map[string]string = make(map[string]string) 20 | var string_array_entries map[string]types.StringArray = make(map[string]types.StringArray) 21 | var plural_string_entries map[string]types.Plural = make(map[string]types.Plural) 22 | 23 | var few_threshold = 20 24 | 25 | const ( 26 | XML types.FileType = "xml" 27 | YAML types.FileType = "yml" 28 | JSON types.FileType = "json" 29 | TOML types.FileType = "toml" 30 | WATSON types.FileType = "watson" 31 | MSGPACK types.FileType = "msgpack" 32 | ) 33 | 34 | var ( 35 | ErrorEmptyStringName error = errors.New("stres: string name can't be empty") 36 | ErrorEmptyStringArrayName error = errors.New("stres: string-array name can't be empty") 37 | ErrorEmptyQuantityStringName error = errors.New("stres: quantity string name can't be empty") 38 | 39 | ErrorDuplicateStringName error = errors.New("stres: string name already inserted") 40 | ErrorDuplicateStringArrayName error = errors.New("stres: string-array name already inserted") 41 | ErrorDuplicateQuantityStringName error = errors.New("stres: quantity string name already inserted") 42 | 43 | ErrorQuantityStringPluralNotFound error = errors.New("stres: plural not found for the given quantity") 44 | 45 | ErrorQuantityStringEmptyValues error = errors.New("stres: provided empty array to quantity string creationg") 46 | ) 47 | 48 | /* 49 | Loads values from strings file into internal dictionaries. 50 | Needs to be invoked only one time (but before getting strings values). 51 | Takes a FileType parameter to specify strings file format. 52 | */ 53 | func LoadValues(t types.FileType) error { 54 | SetResourceType(t) 55 | 56 | var err error 57 | n := &types.Nesting{} 58 | 59 | data, err = readBytes(strings.Join([]string{"./strings/strings.", string(t)}, "")) 60 | if err != nil { 61 | return err 62 | } 63 | 64 | err = encDec.Decode(data, &n) 65 | if err != nil { 66 | return err 67 | } 68 | 69 | var wg sync.WaitGroup 70 | wg.Add(3) 71 | 72 | // Load strings 73 | go func() { 74 | defer wg.Done() 75 | for i := 0; i < len(n.Strings); i++ { 76 | string_entries[n.Strings[i].Name] = n.Strings[i].Value 77 | } 78 | }() 79 | 80 | // Load string arrays 81 | go func() { 82 | defer wg.Done() 83 | for i := 0; i < len(n.StringsArray); i++ { 84 | string_array_entries[n.StringsArray[i].Name] = *n.StringsArray[i] 85 | } 86 | }() 87 | 88 | // Load quantity strings 89 | go func() { 90 | defer wg.Done() 91 | for i := 0; i < len(n.Plurals); i++ { 92 | plural_string_entries[n.Plurals[i].Name] = *n.Plurals[i] 93 | } 94 | }() 95 | 96 | wg.Wait() 97 | 98 | return nil 99 | } 100 | 101 | /* 102 | Used to specify string file extension. If t is a wrong FileType, sets resource type to XML by default. 103 | */ 104 | 105 | func SetResourceType(t types.FileType) { 106 | switch t { 107 | case XML: 108 | xmlED := &types.XMLStrategy{} 109 | encDec.SetStrategy(xmlED) 110 | fileType = XML 111 | case JSON: 112 | jsonED := &types.JSONStrategy{} 113 | encDec.SetStrategy(jsonED) 114 | fileType = JSON 115 | case YAML: 116 | yamlED := &types.YAMLStrategy{} 117 | encDec.SetStrategy(yamlED) 118 | fileType = YAML 119 | case TOML: 120 | tomlED := &types.TOMLStrategy{} 121 | encDec.SetStrategy(tomlED) 122 | fileType = TOML 123 | case WATSON: 124 | watsonED := &types.WatsonStrategy{} 125 | encDec.SetStrategy(watsonED) 126 | fileType = WATSON 127 | case MSGPACK: 128 | msgpackED := &types.MsgPackStrategy{} 129 | encDec.SetStrategy(msgpackED) 130 | fileType = MSGPACK 131 | default: 132 | xmlED := &types.XMLStrategy{} 133 | encDec.SetStrategy(xmlED) 134 | fileType = XML 135 | } 136 | } 137 | 138 | /* 139 | Creates strings resource file in "strings" directory, throws an error otherwise. 140 | Takes a FileType parameter to specify strings file format. 141 | */ 142 | func CreateResourceFile(t types.FileType) (*os.File, error) { 143 | 144 | fileType = t 145 | 146 | SetResourceType(t) 147 | 148 | os.Mkdir("strings", os.ModePerm) 149 | 150 | file, err := os.Create("strings/strings." + string(fileType)) 151 | if err != nil { 152 | return nil, err 153 | } 154 | 155 | _, err = NewString("name", "value") 156 | if err != nil { 157 | return nil, err 158 | } 159 | 160 | return file, nil 161 | } 162 | 163 | /* 164 | Deletes resource file if exists, throws an error otherwise. 165 | Uses setted resource file extension. 166 | */ 167 | func DeleteResourceFile() error { 168 | err := os.Remove("strings/strings." + string(fileType)) 169 | if err != nil { 170 | return err 171 | } 172 | 173 | err = os.Remove("strings") 174 | if err != nil { 175 | return err 176 | } 177 | 178 | return nil 179 | } 180 | 181 | /* 182 | Adds a new string resource to resource file. Throws an error if the chosen name is already inserted or it is an empty string. 183 | */ 184 | func NewString(name, value string) (types.String, error) { 185 | if strings.TrimSpace(name) == "" { 186 | return *new(types.String), ErrorEmptyStringName 187 | } 188 | 189 | if isDuplicateString(name) { 190 | return *new(types.String), ErrorDuplicateStringName 191 | } 192 | 193 | string_entries[name] = value 194 | 195 | var err error 196 | 197 | s := types.String{ 198 | Name: name, 199 | Value: value, 200 | } 201 | 202 | n := &types.Nesting{} 203 | 204 | data, err = readBytes(strings.Join([]string{"./strings/strings.", string(fileType)}, "")) 205 | if err != nil { 206 | return *new(types.String), err 207 | } 208 | 209 | err = encDec.Decode(data, &n) 210 | if err != nil { 211 | return *new(types.String), err 212 | } 213 | n.Strings = append(n.Strings, &s) 214 | 215 | data, err = encDec.Encode(n) 216 | 217 | if err != nil { 218 | return *new(types.String), err 219 | } 220 | 221 | err = writeBytes(strings.Join([]string{"./strings/strings.", string(fileType)}, ""), data) 222 | if err != nil { 223 | return *new(types.String), err 224 | } 225 | 226 | return s, nil 227 | } 228 | 229 | /* 230 | Adds a new string-array resource to resource file. Throws an error if the chosen name is already inserted or it is an empty string. 231 | */ 232 | func NewStringArray(name string, values []string) (types.StringArray, error) { 233 | if strings.TrimSpace(name) == "" { 234 | return *new(types.StringArray), ErrorEmptyStringArrayName 235 | } 236 | 237 | if isDuplicateStringArray(name) { 238 | return *new(types.StringArray), ErrorDuplicateStringArrayName 239 | } 240 | 241 | sa := &types.StringArray{Name: name} 242 | for i := 0; i < len(values); i++ { 243 | item := &types.Item{ 244 | Value: values[i], 245 | } 246 | sa.Items = append(sa.Items, item) 247 | } 248 | 249 | string_array_entries[name] = *sa 250 | 251 | var err error 252 | 253 | n := &types.Nesting{} 254 | 255 | data, err = readBytes("./strings/strings." + string(fileType)) 256 | if err != nil { 257 | return *new(types.StringArray), err 258 | } 259 | 260 | err = encDec.Decode(data, &n) 261 | if err != nil { 262 | return *new(types.StringArray), err 263 | } 264 | n.StringsArray = append(n.StringsArray, sa) 265 | 266 | data, err = encDec.Encode(n) 267 | if err != nil { 268 | return *new(types.StringArray), err 269 | } 270 | 271 | err = writeBytes("strings/strings."+string(fileType), data) 272 | if err != nil { 273 | return *new(types.StringArray), err 274 | } 275 | 276 | return *sa, nil 277 | } 278 | 279 | /* 280 | Adds a new quantity string resource to resource file. 281 | Throws an error if the chosen name is already inserted or it is an empty string. 282 | The function uses only the first 5 values in the array. 283 | The first values is assigned to "zero" quantity. 284 | The second values is assigned to "one" quantity. 285 | The third values is assigned to "two" quantity. 286 | The fourth values is assigned to "few" quantity. 287 | The fifth values is assigned to "more" quantity. 288 | */ 289 | func NewQuantityString(name string, values []string) (types.Plural, error) { 290 | if strings.TrimSpace(name) == "" { 291 | return *new(types.Plural), ErrorEmptyStringArrayName 292 | } 293 | 294 | if len(values) == 0 { 295 | return *new(types.Plural), ErrorQuantityStringEmptyValues 296 | } 297 | 298 | if isDuplicateQuantityString(name) { 299 | return *new(types.Plural), ErrorDuplicateQuantityStringName 300 | } 301 | 302 | pl := &types.Plural{Name: name} 303 | for i := 0; i < len(values) && i < 5; i++ { 304 | item := &types.PluralItem{ 305 | Quantity: quantityValues[i], 306 | Value: values[i], 307 | } 308 | pl.Items = append(pl.Items, item) 309 | } 310 | 311 | plural_string_entries[name] = *pl 312 | 313 | var err error 314 | 315 | n := &types.Nesting{} 316 | 317 | data, err = readBytes("./strings/strings." + string(fileType)) 318 | if err != nil { 319 | return *new(types.Plural), err 320 | } 321 | 322 | err = encDec.Decode(data, &n) 323 | if err != nil { 324 | return *new(types.Plural), err 325 | } 326 | n.Plurals = append(n.Plurals, pl) 327 | 328 | data, err = encDec.Encode(n) 329 | if err != nil { 330 | return *new(types.Plural), err 331 | } 332 | 333 | err = writeBytes("strings/strings."+string(fileType), data) 334 | if err != nil { 335 | return *new(types.Plural), err 336 | } 337 | 338 | return *pl, nil 339 | } 340 | 341 | /* 342 | Sets the threshold for "few" values in quantity strings. 343 | When getting quantity strings values, the function checks if the given count is less OR EQUAL to this value. 344 | (default value: 20) 345 | */ 346 | func SetFewThreshold(value int) { 347 | few_threshold = value 348 | } 349 | 350 | /* 351 | Returns the string resource's value with the given name. If not exists, returns empty string. 352 | */ 353 | func GetString(name string) string { 354 | if name == "" { 355 | return "" 356 | } 357 | if val, ok := string_entries[name]; ok { 358 | return val 359 | } 360 | return "" 361 | } 362 | 363 | /* 364 | Returns the string-array resource's values with the given name. If not exists, returns nil. 365 | */ 366 | func GetArrayString(name string) []string { 367 | if name == "" { 368 | return nil 369 | } 370 | 371 | var arr []string 372 | 373 | if _, ok := string_array_entries[name]; ok { 374 | for i := 0; i < len(string_array_entries[name].Items); i++ { 375 | item := string_array_entries[name].Items 376 | el := item[i].Value 377 | arr = append(arr, el) 378 | } 379 | return arr 380 | } 381 | return nil 382 | } 383 | 384 | /* 385 | Returns the quantity string resource's corresponding string value based on the value of the given count parameter. 386 | If the plural is not found, returns an empty string. 387 | */ 388 | func GetQuantityString(name string, count int) string { 389 | if name == "" { 390 | return "" 391 | } 392 | 393 | idx := -1 394 | 395 | val, exists := plural_string_entries[name] 396 | 397 | if !exists { 398 | return "" 399 | } 400 | 401 | if count == 0 { 402 | idx = 0 403 | } 404 | 405 | if count == 1 { 406 | idx = 1 407 | } 408 | 409 | if count == 2 { 410 | idx = 2 411 | } 412 | 413 | if count > 2 && count <= few_threshold { 414 | idx = 3 415 | } 416 | 417 | if idx == -1 { 418 | idx = 4 419 | } 420 | 421 | for i := 0; i < len(val.Items); i++ { 422 | if val.Items[i].Quantity == quantityValues[idx] { 423 | return val.Items[i].Value 424 | } 425 | } 426 | return "" 427 | } 428 | 429 | func readBytes(path string) ([]byte, error) { 430 | d, err := ioutil.ReadFile(path) 431 | if err != nil { 432 | return *new([]byte), err 433 | } 434 | return d, nil 435 | } 436 | 437 | func isDuplicateString(name string) bool { 438 | if _, ok := string_entries[name]; ok { 439 | return true 440 | } 441 | return false 442 | } 443 | 444 | func isDuplicateStringArray(name string) bool { 445 | if _, ok := string_array_entries[name]; ok { 446 | return true 447 | } 448 | return false 449 | } 450 | 451 | func isDuplicateQuantityString(name string) bool { 452 | if _, ok := plural_string_entries[name]; ok { 453 | return true 454 | } 455 | return false 456 | } 457 | 458 | func writeBytes(path string, data []byte) error { 459 | return os.WriteFile(path, data, 0666) 460 | } 461 | -------------------------------------------------------------------------------- /stres_test.go: -------------------------------------------------------------------------------- 1 | package stres 2 | 3 | import ( 4 | "encoding/xml" 5 | "reflect" 6 | "testing" 7 | 8 | "github.com/Vinetwigs/stres/types" 9 | ) 10 | 11 | func TestNewString(t *testing.T) { 12 | type args struct { 13 | name string 14 | value string 15 | } 16 | tests := []struct { 17 | name string 18 | args args 19 | want types.String 20 | wantErr bool 21 | }{ 22 | { 23 | name: "test_success", 24 | args: args{ 25 | name: "new_string", 26 | value: "value", 27 | }, 28 | want: String{ 29 | XMLName: xml.Name{}, 30 | Name: "new_string", 31 | Value: "value", 32 | }, 33 | wantErr: false, 34 | }, 35 | { 36 | name: "test_error_empty", 37 | args: args{ 38 | name: "", 39 | value: "value", 40 | }, 41 | want: String{ 42 | XMLName: xml.Name{}, 43 | Name: "", 44 | Value: "", 45 | }, 46 | wantErr: true, 47 | }, 48 | { 49 | name: "test_error_duplicated", 50 | args: args{ 51 | name: "new_string", 52 | value: "value_2", 53 | }, 54 | want: String{ 55 | XMLName: xml.Name{}, 56 | Name: "", 57 | Value: "", 58 | }, 59 | wantErr: true, 60 | }, 61 | } 62 | for _, tt := range tests { 63 | t.Run(tt.name, func(t *testing.T) { 64 | got, err := NewString(tt.args.name, tt.args.value) 65 | if (err != nil) != tt.wantErr { 66 | t.Errorf("NewString() error = %v, wantErr %v", err, tt.wantErr) 67 | return 68 | } 69 | if !reflect.DeepEqual(got, tt.want) { 70 | t.Errorf("NewString() = %v, want %v", got, tt.want) 71 | } 72 | }) 73 | } 74 | } 75 | 76 | func TestNewStringArray(t *testing.T) { 77 | type args struct { 78 | name string 79 | values []string 80 | } 81 | tests := []struct { 82 | name string 83 | args args 84 | want StringArray 85 | wantErr bool 86 | }{ 87 | { 88 | name: "test_success", 89 | args: args{ 90 | name: "new_string_array", 91 | values: []string{"1", "2", "3", "4", "5"}, 92 | }, 93 | want: StringArray{ 94 | XMLName: xml.Name{}, 95 | Name: "new_string_array", 96 | Items: []*Item{ 97 | { 98 | XMLName: xml.Name{}, 99 | Value: "1", 100 | }, 101 | { 102 | XMLName: xml.Name{}, 103 | Value: "2", 104 | }, 105 | { 106 | XMLName: xml.Name{}, 107 | Value: "3", 108 | }, 109 | { 110 | XMLName: xml.Name{}, 111 | Value: "4", 112 | }, 113 | { 114 | XMLName: xml.Name{}, 115 | Value: "5", 116 | }, 117 | }, 118 | }, 119 | wantErr: false, 120 | }, 121 | { 122 | name: "test_error_empty", 123 | args: args{ 124 | name: "", 125 | values: []string{"1", "2", "3", "4", "5"}, 126 | }, 127 | want: StringArray{ 128 | XMLName: xml.Name{}, 129 | Name: "", 130 | Items: nil, 131 | }, 132 | wantErr: true, 133 | }, 134 | { 135 | name: "test_error_duplicated", 136 | args: args{ 137 | name: "new_string_array", 138 | values: []string{"1", "2", "3", "4", "5"}, 139 | }, 140 | want: StringArray{ 141 | XMLName: xml.Name{}, 142 | Name: "", 143 | Items: nil, 144 | }, 145 | wantErr: true, 146 | }, 147 | } 148 | for _, tt := range tests { 149 | t.Run(tt.name, func(t *testing.T) { 150 | got, err := NewStringArray(tt.args.name, tt.args.values) 151 | if (err != nil) != tt.wantErr { 152 | t.Errorf("NewStringArray() error = %v, wantErr %v", err, tt.wantErr) 153 | return 154 | } 155 | if !reflect.DeepEqual(got, tt.want) { 156 | t.Errorf("NewStringArray() = %v, want %v", got, tt.want) 157 | } 158 | }) 159 | } 160 | } 161 | 162 | func TestNewQuantityString(t *testing.T) { 163 | type args struct { 164 | name string 165 | values []string 166 | } 167 | tests := []struct { 168 | name string 169 | args args 170 | want Plural 171 | wantErr bool 172 | }{ 173 | { 174 | name: "test_success_partial", 175 | args: args{ 176 | name: "new_quantity_string", 177 | values: []string{"zero", "one", "two"}, 178 | }, 179 | want: Plural{ 180 | XMLName: xml.Name{}, 181 | Name: "new_quantity_string", 182 | Items: []*PluralItem{ 183 | { 184 | XMLName: xml.Name{}, 185 | Quantity: "zero", 186 | Value: "zero", 187 | }, 188 | { 189 | XMLName: xml.Name{}, 190 | Quantity: "one", 191 | Value: "one", 192 | }, 193 | { 194 | XMLName: xml.Name{}, 195 | Quantity: "two", 196 | Value: "two", 197 | }, 198 | }, 199 | }, 200 | wantErr: false, 201 | }, 202 | { 203 | name: "test_success_exceed", 204 | args: args{ 205 | name: "new_quantity_string_two", 206 | values: []string{"zero", "one", "two", "few", "many", "another", "another_one"}, 207 | }, 208 | want: Plural{ 209 | XMLName: xml.Name{}, 210 | Name: "new_quantity_string_two", 211 | Items: []*PluralItem{ 212 | { 213 | XMLName: xml.Name{}, 214 | Quantity: "zero", 215 | Value: "zero", 216 | }, 217 | { 218 | XMLName: xml.Name{}, 219 | Quantity: "one", 220 | Value: "one", 221 | }, 222 | { 223 | XMLName: xml.Name{}, 224 | Quantity: "two", 225 | Value: "two", 226 | }, 227 | { 228 | XMLName: xml.Name{}, 229 | Quantity: "few", 230 | Value: "few", 231 | }, 232 | { 233 | XMLName: xml.Name{}, 234 | Quantity: "many", 235 | Value: "many", 236 | }, 237 | }, 238 | }, 239 | wantErr: false, 240 | }, 241 | { 242 | name: "test_error_empty", 243 | args: args{ 244 | name: "", 245 | values: []string{"one"}, 246 | }, 247 | want: Plural{ 248 | XMLName: xml.Name{}, 249 | Name: "", 250 | Items: nil, 251 | }, 252 | wantErr: true, 253 | }, 254 | { 255 | name: "test_error_duplicated", 256 | args: args{ 257 | name: "new_quantity_string", 258 | values: []string{"one"}, 259 | }, 260 | want: Plural{ 261 | XMLName: xml.Name{}, 262 | Name: "", 263 | Items: nil, 264 | }, 265 | wantErr: true, 266 | }, 267 | { 268 | name: "test_success_full", 269 | args: args{ 270 | name: "new_quantity_string_three", 271 | values: []string{"zero", "one", "two", "few", "many"}, 272 | }, 273 | want: Plural{ 274 | XMLName: xml.Name{}, 275 | Name: "new_quantity_string_three", 276 | Items: []*PluralItem{ 277 | { 278 | XMLName: xml.Name{}, 279 | Quantity: "zero", 280 | Value: "zero", 281 | }, 282 | { 283 | XMLName: xml.Name{}, 284 | Quantity: "one", 285 | Value: "one", 286 | }, 287 | { 288 | XMLName: xml.Name{}, 289 | Quantity: "two", 290 | Value: "two", 291 | }, 292 | { 293 | XMLName: xml.Name{}, 294 | Quantity: "few", 295 | Value: "few", 296 | }, 297 | { 298 | XMLName: xml.Name{}, 299 | Quantity: "many", 300 | Value: "many", 301 | }, 302 | }, 303 | }, 304 | wantErr: false, 305 | }, 306 | { 307 | name: "test_error_empty", 308 | args: args{ 309 | name: "", 310 | values: []string{"one"}, 311 | }, 312 | want: Plural{ 313 | XMLName: xml.Name{}, 314 | Name: "", 315 | Items: nil, 316 | }, 317 | wantErr: true, 318 | }, 319 | { 320 | name: "test_error_no_values", 321 | args: args{ 322 | name: "new_quantity_string", 323 | values: []string{}, 324 | }, 325 | want: Plural{ 326 | XMLName: xml.Name{}, 327 | Name: "", 328 | Items: nil, 329 | }, 330 | wantErr: true, 331 | }, 332 | } 333 | for _, tt := range tests { 334 | t.Run(tt.name, func(t *testing.T) { 335 | got, err := NewQuantityString(tt.args.name, tt.args.values) 336 | if (err != nil) != tt.wantErr { 337 | t.Errorf("NewQuantityString() error = %v, wantErr %v", err, tt.wantErr) 338 | return 339 | } 340 | if !reflect.DeepEqual(got, tt.want) { 341 | t.Errorf("NewQuantityString() = %v, want %v", got, tt.want) 342 | } 343 | }) 344 | } 345 | } 346 | 347 | func TestSetFewThreshold(t *testing.T) { 348 | type args struct { 349 | value int 350 | } 351 | tests := []struct { 352 | name string 353 | args args 354 | }{ 355 | { 356 | name: "set_threshold_success", 357 | args: args{ 358 | value: 25, 359 | }, 360 | }, 361 | } 362 | for _, tt := range tests { 363 | t.Run(tt.name, func(t *testing.T) { 364 | SetFewThreshold(tt.args.value) 365 | }) 366 | } 367 | } 368 | 369 | func TestGetString(t *testing.T) { 370 | type args struct { 371 | name string 372 | } 373 | tests := []struct { 374 | name string 375 | args args 376 | want string 377 | }{ 378 | { 379 | name: "test_success", 380 | args: args{ 381 | name: "get_string", 382 | }, 383 | want: "value", 384 | }, 385 | { 386 | name: "test_error_inexistent", 387 | args: args{ 388 | name: "get_string_two", 389 | }, 390 | want: "", 391 | }, 392 | { 393 | name: "test_error_empty", 394 | args: args{ 395 | name: "", 396 | }, 397 | want: "", 398 | }, 399 | } 400 | for _, tt := range tests { 401 | NewString("get_string", "value") 402 | t.Run(tt.name, func(t *testing.T) { 403 | if got := GetString(tt.args.name); got != tt.want { 404 | t.Errorf("GetString() = %v, want %v", got, tt.want) 405 | } 406 | }) 407 | } 408 | } 409 | 410 | func TestGetArrayString(t *testing.T) { 411 | type args struct { 412 | name string 413 | } 414 | tests := []struct { 415 | name string 416 | args args 417 | want []string 418 | }{ 419 | { 420 | name: "test_success", 421 | args: args{ 422 | name: "get_string_array", 423 | }, 424 | want: []string{"value1", "value2", "value3"}, 425 | }, 426 | { 427 | name: "test_error_inexistent", 428 | args: args{ 429 | name: "get_string_array_two", 430 | }, 431 | want: nil, 432 | }, 433 | { 434 | name: "test_error_empty", 435 | args: args{ 436 | name: "", 437 | }, 438 | want: nil, 439 | }, 440 | } 441 | NewStringArray("get_string_array", []string{"value1", "value2", "value3"}) 442 | for _, tt := range tests { 443 | t.Run(tt.name, func(t *testing.T) { 444 | if got := GetArrayString(tt.args.name); !reflect.DeepEqual(got, tt.want) { 445 | t.Errorf("GetArrayString() = %v, want %v", got, tt.want) 446 | } 447 | }) 448 | } 449 | } 450 | 451 | func TestGetQuantityString(t *testing.T) { 452 | type args struct { 453 | name string 454 | count int 455 | } 456 | tests := []struct { 457 | name string 458 | args args 459 | want string 460 | }{ 461 | { 462 | name: "test_success_zero", 463 | args: args{ 464 | name: "get_quantity_string", 465 | count: 0, 466 | }, 467 | want: "zero", 468 | }, 469 | { 470 | name: "test_success_one", 471 | args: args{ 472 | name: "get_quantity_string", 473 | count: 1, 474 | }, 475 | want: "one", 476 | }, 477 | { 478 | name: "test_success_two", 479 | args: args{ 480 | name: "get_quantity_string", 481 | count: 2, 482 | }, 483 | want: "two", 484 | }, 485 | { 486 | name: "test_success_few", 487 | args: args{ 488 | name: "get_quantity_string", 489 | count: 15, 490 | }, 491 | want: "few", 492 | }, 493 | { 494 | name: "test_success_many", 495 | args: args{ 496 | name: "get_quantity_string", 497 | count: 420, 498 | }, 499 | want: "many", 500 | }, 501 | { 502 | name: "test_error_empty", 503 | args: args{ 504 | name: "", 505 | count: 0, 506 | }, 507 | want: "", 508 | }, 509 | { 510 | name: "test_error_zero", 511 | args: args{ 512 | name: "errorZero", 513 | count: 0, 514 | }, 515 | want: "", 516 | }, 517 | { 518 | name: "test_error_one", 519 | args: args{ 520 | name: "errorOne", 521 | count: 1, 522 | }, 523 | want: "", 524 | }, 525 | { 526 | name: "test_error_two", 527 | args: args{ 528 | name: "errorTwo", 529 | count: 2, 530 | }, 531 | want: "", 532 | }, 533 | { 534 | name: "test_error_few", 535 | args: args{ 536 | name: "errorFew", 537 | count: 15, 538 | }, 539 | want: "", 540 | }, 541 | { 542 | name: "test_error_many", 543 | args: args{ 544 | name: "errorMany", 545 | count: 420, 546 | }, 547 | want: "", 548 | }, 549 | } 550 | NewQuantityString("get_quantity_string", []string{"zero", "one", "two", "few", "many"}) 551 | NewQuantityString("errorZero", []string{""}) 552 | NewQuantityString("errorOne", []string{"zero"}) 553 | NewQuantityString("errorTwo", []string{"zero", "one"}) 554 | NewQuantityString("errorFew", []string{"zero", "one", "two"}) 555 | NewQuantityString("errorMany", []string{"zero", "one", "two", "few"}) 556 | for _, tt := range tests { 557 | t.Run(tt.name, func(t *testing.T) { 558 | if got := GetQuantityString(tt.args.name, tt.args.count); got != tt.want { 559 | t.Errorf("GetQuantityString() = %v, want %v", got, tt.want) 560 | } 561 | }) 562 | } 563 | } 564 | 565 | func Test_isDuplicateString(t *testing.T) { 566 | type args struct { 567 | name string 568 | } 569 | tests := []struct { 570 | name string 571 | args args 572 | want bool 573 | }{ 574 | { 575 | name: "test_duplicate", 576 | args: args{ 577 | name: "string_duplicate_test", 578 | }, 579 | want: true, 580 | }, 581 | { 582 | name: "test_not_duplicate", 583 | args: args{ 584 | name: "string_duplicate_test_two", 585 | }, 586 | want: false, 587 | }, 588 | } 589 | NewString("string_duplicate_test", "value") 590 | for _, tt := range tests { 591 | t.Run(tt.name, func(t *testing.T) { 592 | if got := isDuplicateString(tt.args.name); got != tt.want { 593 | t.Errorf("isDuplicateString() = %v, want %v", got, tt.want) 594 | } 595 | }) 596 | } 597 | } 598 | 599 | func Test_isDuplicateStringArray(t *testing.T) { 600 | type args struct { 601 | name string 602 | } 603 | tests := []struct { 604 | name string 605 | args args 606 | want bool 607 | }{ 608 | { 609 | name: "test_duplicate", 610 | args: args{ 611 | name: "string_array_duplicate_test", 612 | }, 613 | want: true, 614 | }, 615 | { 616 | name: "test_not_duplicate", 617 | args: args{ 618 | name: "string_array_duplicate_test_two", 619 | }, 620 | want: false, 621 | }, 622 | } 623 | NewStringArray("string_array_duplicate_test", []string{"test"}) 624 | for _, tt := range tests { 625 | t.Run(tt.name, func(t *testing.T) { 626 | if got := isDuplicateStringArray(tt.args.name); got != tt.want { 627 | t.Errorf("isDuplicateStringArray() = %v, want %v", got, tt.want) 628 | } 629 | }) 630 | } 631 | } 632 | 633 | func Test_isDuplicateQuantityString(t *testing.T) { 634 | type args struct { 635 | name string 636 | } 637 | tests := []struct { 638 | name string 639 | args args 640 | want bool 641 | }{ 642 | { 643 | name: "test_duplicate", 644 | args: args{ 645 | name: "quantity_string_duplicate_test", 646 | }, 647 | want: true, 648 | }, 649 | { 650 | name: "test_not_duplicate", 651 | args: args{ 652 | name: "quantity_string_duplicate_test_two", 653 | }, 654 | want: false, 655 | }, 656 | } 657 | NewQuantityString("quantity_string_duplicate_test", []string{"test"}) 658 | for _, tt := range tests { 659 | t.Run(tt.name, func(t *testing.T) { 660 | if got := isDuplicateQuantityString(tt.args.name); got != tt.want { 661 | t.Errorf("isDuplicateQuantityString() = %v, want %v", got, tt.want) 662 | } 663 | }) 664 | } 665 | } 666 | --------------------------------------------------------------------------------