├── Doc ├── AUTHORS.md ├── CONTRIBUTORS.md ├── LICENSE_Apache.txt └── NEWS.md ├── README.md ├── all_test.go ├── config.go ├── error.go ├── option.go ├── read.go ├── section.go ├── testdata ├── source.cfg └── target.cfg ├── type.go └── write.go /Doc/AUTHORS.md: -------------------------------------------------------------------------------- 1 | ###### Notice 2 | 3 | *This is the official list of **config** authors for copyright purposes.* 4 | 5 | *This file is distinct from the CONTRIBUTORS file. See the latter for an 6 | explanation.* 7 | 8 | *Names should be added to this file as: `Organization`; 9 | `[Name](web address)` or `Name ` for individuals* 10 | 11 | *Please keep the list sorted.* 12 | 13 | * * * 14 | 15 | [Jonas mg](https://github.com/kless) 16 | [Miguel Branco](https://github.com/msbranco) 17 | [Rob Figueiredo](https://github.com/robfig) 18 | [Tom Bruggeman](https://github.com/tmbrggmn) 19 | 20 | -------------------------------------------------------------------------------- /Doc/CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | ###### Notice 2 | 3 | *This is the official list of people who can contribute (and typically have 4 | contributed) code to the **config** repository.* 5 | 6 | *The AUTHORS file lists the copyright holders; this file lists people. For 7 | example, the employees of an organization are listed here but not in AUTHORS, 8 | because the organization holds the copyright.* 9 | 10 | *Names should be added to this file as: `[Name](web address)` or `Name `* 11 | 12 | *Please keep the list sorted.* 13 | 14 | * * * 15 | 16 | ### Initial author 17 | 18 | [Miguel Branco](https://github.com/msbranco) 19 | 20 | ### Maintainer 21 | 22 | [Rob Figueiredo](https://github.com/robfig) 23 | 24 | ### Other authors 25 | 26 | [Jonas mg](https://github.com/kless) 27 | [Tom Bruggeman](https://github.com/tmbrggmn) 28 | 29 | -------------------------------------------------------------------------------- /Doc/LICENSE_Apache.txt: -------------------------------------------------------------------------------- 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 | 203 | -------------------------------------------------------------------------------- /Doc/NEWS.md: -------------------------------------------------------------------------------- 1 | ###### Notice 2 | 3 | *This file documents the changes in **config** versions that are listed below.* 4 | 5 | *Items should be added to this file as:* 6 | 7 | ### YYYY-MM-DD Release 8 | 9 | + Additional changes. 10 | 11 | + More changes. 12 | 13 | * * * 14 | 15 | ### 2011-??-?? v0.9.6 16 | 17 | + Changed to line comments. 18 | 19 | 20 | ### 2010-09-15 v0.9.5 21 | 22 | + Sections, options and values are all case-sensitive. 23 | 24 | + Changed API: 25 | 26 | Type *File* -> *Config* 27 | *NewFile()* -> *NewDefault* 28 | *ReadFile()* -> *ReadDefault* 29 | 30 | + Added functions, *New()*, *Read()*, which allow to choose the character of 31 | comment and separator, and the spaces around separator. 32 | 33 | + Better error handling. 34 | 35 | + Both sections and options are showed by its input order. 36 | 37 | 38 | ### 2010-08-22 v0.9 39 | 40 | + The files has been splitted, formatted via *gomft*. 41 | 42 | + Methods use *self* to refer to its own type. 43 | 44 | + *Get* has been removed from the functions names. 45 | 46 | + Fixed some errors. All tests are passed. 47 | 48 | + At write the header in configuration file, it is added the comment character 49 | after of each new line. 50 | 51 | + Better documentation. 52 | 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | config 2 | ====== 3 | 4 | This package implements a basic configuration file parser language which 5 | provides a structure similar to what you would find on Microsoft Windows INI 6 | files. 7 | 8 | The configuration file consists of sections, led by a "*[section]*" header and 9 | followed by "*name: value*" entries; "*name=value*" is also accepted. Note that 10 | leading whitespace is removed from values. The optional values can contain 11 | format strings which refer to other values in the same section, or values in a 12 | special *DEFAULT* section. Additional defaults can be provided on initialization 13 | and retrieval. Comments are indicated by ";" or "#"; a comment may begin 14 | anywhere on a line, including on the same line after parameters or section 15 | declarations. 16 | 17 | For example: 18 | 19 | [My Section] 20 | foodir: %(dir)s/whatever 21 | dir=foo 22 | 23 | would resolve the "*%(dir)s*" to the value of "*dir*" (*foo* in this case). All 24 | reference expansions are done on demand. 25 | 26 | The functionality and workflow is loosely based on the *configparser* package of 27 | the Python Standard Library. 28 | 29 | ## Installation 30 | 31 | go get github.com/robfig/config 32 | 33 | ## Operating instructions 34 | 35 | Given a sample configuration file: 36 | 37 | [DEFAULT] 38 | host: www.example.com 39 | protocol: http:// 40 | base-url: %(protocol)s%(host)s 41 | 42 | [service-1] 43 | url: %(base-url)s/some/path 44 | delegation: on 45 | maxclients: 200 # do not set this higher 46 | comments: This is a multi-line 47 | entry # And this is a comment 48 | 49 | To read this configuration file, do: 50 | 51 | c, _ := config.ReadDefault("config.cfg") 52 | 53 | c.String("service-1", "url") 54 | // result is string "http://www.example.com/some/path" 55 | 56 | c.Int("service-1", "maxclients") 57 | // result is int 200 58 | 59 | c.Bool("service-1", "delegation") 60 | // result is bool true 61 | 62 | c.String("service-1", "comments") 63 | // result is string "This is a multi-line\nentry" 64 | 65 | Note the support for unfolding variables (such as *%(base-url)s*), which are read 66 | from the special (reserved) section name *[DEFAULT]*. 67 | 68 | A new configuration file can also be created with: 69 | 70 | c := config.NewDefault() 71 | c.AddSection("Section") 72 | c.AddOption("Section", "option", "value") 73 | c.WriteFile("config.cfg", 0644, "A header for this file") 74 | 75 | This results in the file: 76 | 77 | # A header for this file 78 | 79 | [Section] 80 | option: value 81 | 82 | Note that sections, options and values are all case-sensitive. 83 | 84 | ## License 85 | 86 | The source files are distributed under the [Mozilla Public License, version 2.0](http://mozilla.org/MPL/2.0/), 87 | unless otherwise noted. 88 | Please read the [FAQ](http://www.mozilla.org/MPL/2.0/FAQ.html) 89 | if you have further questions regarding the license. 90 | 91 | -------------------------------------------------------------------------------- /all_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import ( 18 | "bufio" 19 | "os" 20 | "reflect" 21 | "strings" 22 | "testing" 23 | ) 24 | 25 | const ( 26 | tmpFilename = "testdata/__test.go" 27 | sourceFilename = "testdata/source.cfg" 28 | targetFilename = "testdata/target.cfg" 29 | ) 30 | 31 | func testGet(t *testing.T, c *Config, section string, option string, 32 | expected interface{}) { 33 | ok := false 34 | switch expected.(type) { 35 | case string: 36 | v, _ := c.String(section, option) 37 | if v == expected.(string) { 38 | ok = true 39 | } 40 | case int: 41 | v, _ := c.Int(section, option) 42 | if v == expected.(int) { 43 | ok = true 44 | } 45 | case bool: 46 | v, _ := c.Bool(section, option) 47 | if v == expected.(bool) { 48 | ok = true 49 | } 50 | default: 51 | t.Fatalf("Bad test case") 52 | } 53 | if !ok { 54 | v, _ := c.String(section, option) 55 | t.Errorf("Get failure: expected different value for %s %s (expected: [%#v] got: [%#v])", section, option, expected, v) 56 | } 57 | } 58 | 59 | // TestInMemory creates configuration representation and run multiple tests in-memory. 60 | func TestInMemory(t *testing.T) { 61 | c := NewDefault() 62 | 63 | // == Test empty structure 64 | 65 | // should be empty 66 | if len(c.Sections()) != 1 { 67 | t.Errorf("Sections failure: invalid length") 68 | } 69 | 70 | // test presence of missing section 71 | if c.HasSection("no-section") { 72 | t.Errorf("HasSection failure: invalid section") 73 | } 74 | 75 | // get options for missing section 76 | _, err := c.Options("no-section") 77 | if err == nil { 78 | t.Errorf("Options failure: invalid section") 79 | } 80 | 81 | // test presence of option for missing section 82 | if c.HasOption("no-section", "no-option") { 83 | t.Errorf("HasSection failure: invalid/section/option") 84 | } 85 | 86 | // get value from missing section/option 87 | _, err = c.String("no-section", "no-option") 88 | if err == nil { 89 | t.Errorf("String failure: got value for missing section/option") 90 | } 91 | 92 | // get value from missing section/option 93 | _, err = c.Int("no-section", "no-option") 94 | if err == nil { 95 | t.Errorf("Int failure: got value for missing section/option") 96 | } 97 | 98 | // remove missing section 99 | if c.RemoveSection("no-section") { 100 | t.Errorf("RemoveSection failure: removed missing section") 101 | } 102 | 103 | // remove missing section/option 104 | if c.RemoveOption("no-section", "no-option") { 105 | t.Errorf("RemoveOption failure: removed missing section/option") 106 | } 107 | 108 | // == Fill up structure 109 | 110 | // add section 111 | if !c.AddSection("section1") { 112 | t.Errorf("AddSection failure: false on first insert") 113 | } 114 | 115 | // re-add same section 116 | if c.AddSection("section1") { 117 | t.Errorf("AddSection failure: true on second insert") 118 | } 119 | 120 | // default section always exists 121 | if c.AddSection(DEFAULT_SECTION) { 122 | t.Errorf("AddSection failure: true on default section insert") 123 | } 124 | 125 | // add option/value 126 | if !c.AddOption("section1", "option1", "value1") { 127 | t.Errorf("AddOption failure: false on first insert") 128 | } 129 | testGet(t, c, "section1", "option1", "value1") // read it back 130 | 131 | // overwrite value 132 | if c.AddOption("section1", "option1", "value2") { 133 | t.Errorf("AddOption failure: true on second insert") 134 | } 135 | testGet(t, c, "section1", "option1", "value2") // read it back again 136 | 137 | // remove option/value 138 | if !c.RemoveOption("section1", "option1") { 139 | t.Errorf("RemoveOption failure: false on first remove") 140 | } 141 | 142 | // remove again 143 | if c.RemoveOption("section1", "option1") { 144 | t.Errorf("RemoveOption failure: true on second remove") 145 | } 146 | 147 | // read it back again 148 | _, err = c.String("section1", "option1") 149 | if err == nil { 150 | t.Errorf("String failure: got value for removed section/option") 151 | } 152 | 153 | // remove existing section 154 | if !c.RemoveSection("section1") { 155 | t.Errorf("RemoveSection failure: false on first remove") 156 | } 157 | 158 | // remove again 159 | if c.RemoveSection("section1") { 160 | t.Errorf("RemoveSection failure: true on second remove") 161 | } 162 | 163 | // == Test types 164 | 165 | // add section 166 | if !c.AddSection("section2") { 167 | t.Errorf("AddSection failure: false on first insert") 168 | } 169 | 170 | // add number 171 | if !c.AddOption("section2", "test-number", "666") { 172 | t.Errorf("AddOption failure: false on first insert") 173 | } 174 | testGet(t, c, "section2", "test-number", 666) // read it back 175 | 176 | // add 'yes' (bool) 177 | if !c.AddOption("section2", "test-yes", "yes") { 178 | t.Errorf("AddOption failure: false on first insert") 179 | } 180 | testGet(t, c, "section2", "test-yes", true) // read it back 181 | 182 | // add 'false' (bool) 183 | if !c.AddOption("section2", "test-false", "false") { 184 | t.Errorf("AddOption failure: false on first insert") 185 | } 186 | testGet(t, c, "section2", "test-false", false) // read it back 187 | 188 | // == Test cycle 189 | 190 | c.AddOption(DEFAULT_SECTION, "opt1", "%(opt2)s") 191 | c.AddOption(DEFAULT_SECTION, "opt2", "%(opt1)s") 192 | 193 | _, err = c.String(DEFAULT_SECTION, "opt1") 194 | if err == nil { 195 | t.Errorf("String failure: no error for cycle") 196 | } else if strings.Index(err.Error(), "cycle") < 0 { 197 | t.Errorf("String failure: incorrect error for cycle") 198 | } 199 | } 200 | 201 | // TestReadFile creates a 'tough' configuration file and test (read) parsing. 202 | func TestReadFile(t *testing.T) { 203 | file, err := os.Create(tmpFilename) 204 | if err != nil { 205 | t.Fatal("Test cannot run because cannot write temporary file: " + tmpFilename) 206 | } 207 | 208 | err = os.Setenv("GO_CONFIGFILE_TEST_ENV_VAR", "configvalue12345") 209 | if err != nil { 210 | t.Fatalf("Test cannot run because cannot set environment variable GO_CONFIGFILE_TEST_ENV_VAR: %#v", err) 211 | } 212 | 213 | buf := bufio.NewWriter(file) 214 | buf.WriteString("optionInDefaultSection=true\n") 215 | buf.WriteString("[section-1]\n") 216 | buf.WriteString("option1=value1 ; This is a comment\n") 217 | buf.WriteString("option2 : 2#Not a comment\t#Now this is a comment after a TAB\n") 218 | buf.WriteString(" # Let me put another comment\n") 219 | buf.WriteString("option3= line1\n line2: \n\tline3=v # Comment multiline with := in value\n") 220 | buf.WriteString("; Another comment\n") 221 | buf.WriteString("[" + DEFAULT_SECTION + "]\n") 222 | buf.WriteString("variable1=small\n") 223 | buf.WriteString("variable2=a_part_of_a_%(variable1)s_test\n") 224 | buf.WriteString("[secTION-2]\n") 225 | buf.WriteString("IS-flag-TRUE=Yes\n") 226 | buf.WriteString("[section-1] # comment on section header\n") // continue again [section-1] 227 | buf.WriteString("option4=this_is_%(variable2)s.\n") 228 | buf.WriteString("envoption1=this_uses_${GO_CONFIGFILE_TEST_ENV_VAR}_env\n") 229 | buf.WriteString("optionInDefaultSection=false") 230 | buf.Flush() 231 | file.Close() 232 | 233 | c, err := ReadDefault(tmpFilename) 234 | if err != nil { 235 | t.Fatalf("ReadDefault failure: %s", err) 236 | } 237 | 238 | // check number of sections 239 | if len(c.Sections()) != 3 { 240 | t.Errorf("Sections failure: wrong number of sections") 241 | } 242 | 243 | // check number of options 6 of [section-1] plus 2 of [default] 244 | opts, err := c.Options("section-1") 245 | if len(opts) != 8 { 246 | t.Errorf("Options failure: wrong number of options: %d", len(opts)) 247 | } 248 | 249 | testGet(t, c, "section-1", "option1", "value1") 250 | testGet(t, c, "section-1", "option2", "2#Not a comment") 251 | testGet(t, c, "section-1", "option3", "line1\nline2:\nline3=v") 252 | testGet(t, c, "section-1", "option4", "this_is_a_part_of_a_small_test.") 253 | testGet(t, c, "section-1", "envoption1", "this_uses_configvalue12345_env") 254 | testGet(t, c, "section-1", "optionInDefaultSection", false) 255 | testGet(t, c, "section-2", "optionInDefaultSection", true) 256 | testGet(t, c, "secTION-2", "IS-flag-TRUE", true) // case-sensitive 257 | } 258 | 259 | // TestWriteReadFile tests writing and reading back a configuration file. 260 | func TestWriteReadFile(t *testing.T) { 261 | cw := NewDefault() 262 | 263 | // write file; will test only read later on 264 | cw.AddSection("First-Section") 265 | cw.AddOption("First-Section", "option1", "value option1") 266 | cw.AddOption("First-Section", "option2", "2") 267 | 268 | cw.AddOption("", "host", "www.example.com") 269 | cw.AddOption(DEFAULT_SECTION, "protocol", "https://") 270 | cw.AddOption(DEFAULT_SECTION, "base-url", "%(protocol)s%(host)s") 271 | 272 | cw.AddOption("Another-Section", "useHTTPS", "y") 273 | cw.AddOption("Another-Section", "url", "%(base-url)s/some/path") 274 | 275 | cw.WriteFile(tmpFilename, 0644, "Test file for test-case") 276 | 277 | // read back file and test 278 | cr, err := ReadDefault(tmpFilename) 279 | if err != nil { 280 | t.Fatalf("ReadDefault failure: %s", err) 281 | } 282 | 283 | testGet(t, cr, "First-Section", "option1", "value option1") 284 | testGet(t, cr, "First-Section", "option2", 2) 285 | testGet(t, cr, "Another-Section", "useHTTPS", true) 286 | testGet(t, cr, "Another-Section", "url", "https://www.example.com/some/path") 287 | 288 | defer os.Remove(tmpFilename) 289 | } 290 | 291 | // TestSectionOptions tests read options in a section without default options. 292 | func TestSectionOptions(t *testing.T) { 293 | cw := NewDefault() 294 | 295 | // write file; will test only read later on 296 | cw.AddSection("First-Section") 297 | cw.AddOption("First-Section", "option1", "value option1") 298 | cw.AddOption("First-Section", "option2", "2") 299 | 300 | cw.AddOption("", "host", "www.example.com") 301 | cw.AddOption(DEFAULT_SECTION, "protocol", "https://") 302 | cw.AddOption(DEFAULT_SECTION, "base-url", "%(protocol)s%(host)s") 303 | 304 | cw.AddOption("Another-Section", "useHTTPS", "y") 305 | cw.AddOption("Another-Section", "url", "%(base-url)s/some/path") 306 | 307 | cw.WriteFile(tmpFilename, 0644, "Test file for test-case") 308 | 309 | // read back file and test 310 | cr, err := ReadDefault(tmpFilename) 311 | if err != nil { 312 | t.Fatalf("ReadDefault failure: %s", err) 313 | } 314 | 315 | options, err := cr.SectionOptions("First-Section") 316 | 317 | if err != nil { 318 | t.Fatalf("SectionOptions failure: %s", err) 319 | } 320 | 321 | if len(options) != 2 { 322 | t.Fatalf("SectionOptions reads wrong data: %v", options) 323 | } 324 | 325 | expected := map[string]bool{ 326 | "option1": true, 327 | "option2": true, 328 | } 329 | actual := map[string]bool{} 330 | 331 | for _, v := range options { 332 | actual[v] = true 333 | } 334 | 335 | if !reflect.DeepEqual(expected, actual) { 336 | t.Fatalf("SectionOptions reads wrong data: %v", options) 337 | } 338 | 339 | options, err = cr.SectionOptions(DEFAULT_SECTION) 340 | 341 | if err != nil { 342 | t.Fatalf("SectionOptions failure: %s", err) 343 | } 344 | 345 | expected = map[string]bool{ 346 | "host": true, 347 | "protocol": true, 348 | "base-url": true, 349 | } 350 | actual = map[string]bool{} 351 | 352 | for _, v := range options { 353 | actual[v] = true 354 | } 355 | 356 | if !reflect.DeepEqual(expected, actual) { 357 | t.Fatalf("SectionOptions reads wrong data: %v", options) 358 | } 359 | 360 | defer os.Remove(tmpFilename) 361 | } 362 | 363 | // TestMerge tests merging 2 configurations. 364 | func TestMerge(t *testing.T) { 365 | target, error := ReadDefault(targetFilename) 366 | if error != nil { 367 | t.Fatalf("Unable to read target config file '%s'", targetFilename) 368 | } 369 | 370 | source, error := ReadDefault(sourceFilename) 371 | if error != nil { 372 | t.Fatalf("Unable to read source config file '%s'", sourceFilename) 373 | } 374 | 375 | target.Merge(source) 376 | 377 | // Assert whether a regular option was merged from source -> target 378 | if result, _ := target.String(DEFAULT_SECTION, "one"); result != "source1" { 379 | t.Errorf("Expected 'one' to be '1' but instead it was '%s'", result) 380 | } 381 | // Assert that a non-existent option in source was not overwritten 382 | if result, _ := target.String(DEFAULT_SECTION, "five"); result != "5" { 383 | t.Errorf("Expected 'five' to be '5' but instead it was '%s'", result) 384 | } 385 | // Assert that a folded option was correctly unfolded 386 | if result, _ := target.String(DEFAULT_SECTION, "two_+_three"); result != "source2 + source3" { 387 | t.Errorf("Expected 'two_+_three' to be 'source2 + source3' but instead it was '%s'", result) 388 | } 389 | if result, _ := target.String(DEFAULT_SECTION, "four"); result != "4" { 390 | t.Errorf("Expected 'four' to be '4' but instead it was '%s'", result) 391 | } 392 | 393 | // Assert that a section option has been merged 394 | if result, _ := target.String("X", "x.one"); result != "sourcex1" { 395 | t.Errorf("Expected '[X] x.one' to be 'sourcex1' but instead it was '%s'", result) 396 | } 397 | if result, _ := target.String("X", "x.four"); result != "x4" { 398 | t.Errorf("Expected '[X] x.four' to be 'x4' but instead it was '%s'", result) 399 | } 400 | } 401 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import ( 18 | "regexp" 19 | "strings" 20 | ) 21 | 22 | const ( 23 | // Default section name. 24 | DEFAULT_SECTION = "DEFAULT" 25 | // Maximum allowed depth when recursively substituing variable names. 26 | _DEPTH_VALUES = 200 27 | 28 | DEFAULT_COMMENT = "# " 29 | ALTERNATIVE_COMMENT = "; " 30 | DEFAULT_SEPARATOR = ":" 31 | ALTERNATIVE_SEPARATOR = "=" 32 | ) 33 | 34 | var ( 35 | // Strings accepted as boolean. 36 | boolString = map[string]bool{ 37 | "t": true, 38 | "true": true, 39 | "y": true, 40 | "yes": true, 41 | "on": true, 42 | "1": true, 43 | "f": false, 44 | "false": false, 45 | "n": false, 46 | "no": false, 47 | "off": false, 48 | "0": false, 49 | } 50 | 51 | varRegExp = regexp.MustCompile(`%\(([a-zA-Z0-9_.\-]+)\)s`) // %(variable)s 52 | envVarRegExp = regexp.MustCompile(`\${([a-zA-Z0-9_.\-]+)}`) // ${envvar} 53 | ) 54 | 55 | // Config is the representation of configuration settings. 56 | type Config struct { 57 | comment string 58 | separator string 59 | 60 | // Sections order 61 | lastIdSection int // Last section identifier 62 | idSection map[string]int // Section : position 63 | 64 | // The last option identifier used for each section. 65 | lastIdOption map[string]int // Section : last identifier 66 | 67 | // Section -> option : value 68 | data map[string]map[string]*tValue 69 | } 70 | 71 | // tValue holds the input position for a value. 72 | type tValue struct { 73 | position int // Option order 74 | v string // value 75 | } 76 | 77 | // New creates an empty configuration representation. 78 | // This representation can be filled with AddSection and AddOption and then 79 | // saved to a file using WriteFile. 80 | // 81 | // == Arguments 82 | // 83 | // comment: has to be `DEFAULT_COMMENT` or `ALTERNATIVE_COMMENT` 84 | // separator: has to be `DEFAULT_SEPARATOR` or `ALTERNATIVE_SEPARATOR` 85 | // preSpace: indicate if is inserted a space before of the separator 86 | // postSpace: indicate if is added a space after of the separator 87 | func New(comment, separator string, preSpace, postSpace bool) *Config { 88 | if comment != DEFAULT_COMMENT && comment != ALTERNATIVE_COMMENT { 89 | panic("comment character not valid") 90 | } 91 | 92 | if separator != DEFAULT_SEPARATOR && separator != ALTERNATIVE_SEPARATOR { 93 | panic("separator character not valid") 94 | } 95 | 96 | // == Get spaces around separator 97 | if preSpace { 98 | separator = " " + separator 99 | } 100 | 101 | if postSpace { 102 | separator += " " 103 | } 104 | //== 105 | 106 | c := new(Config) 107 | 108 | c.comment = comment 109 | c.separator = separator 110 | c.idSection = make(map[string]int) 111 | c.lastIdOption = make(map[string]int) 112 | c.data = make(map[string]map[string]*tValue) 113 | 114 | c.AddSection(DEFAULT_SECTION) // Default section always exists. 115 | 116 | return c 117 | } 118 | 119 | // NewDefault creates a configuration representation with values by default. 120 | func NewDefault() *Config { 121 | return New(DEFAULT_COMMENT, DEFAULT_SEPARATOR, false, true) 122 | } 123 | 124 | // Merge merges the given configuration "source" with this one ("target"). 125 | // 126 | // Merging means that any option (under any section) from source that is not in 127 | // target will be copied into target. When the target already has an option with 128 | // the same name and section then it is overwritten (i.o.w. the source wins). 129 | func (target *Config) Merge(source *Config) { 130 | if source == nil || source.data == nil || len(source.data) == 0 { 131 | return 132 | } 133 | 134 | for section, option := range source.data { 135 | for optionName, optionValue := range option { 136 | target.AddOption(section, optionName, optionValue.v) 137 | } 138 | } 139 | } 140 | 141 | // == Utility 142 | 143 | func stripComments(l string) string { 144 | // Comments are preceded by space or TAB 145 | for _, c := range []string{" ;", "\t;", " #", "\t#"} { 146 | if i := strings.Index(l, c); i != -1 { 147 | l = l[0:i] 148 | } 149 | } 150 | return l 151 | } 152 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | type SectionError string 18 | 19 | func (e SectionError) Error() string { 20 | return "section not found: " + string(e) 21 | } 22 | 23 | type OptionError string 24 | 25 | func (e OptionError) Error() string { 26 | return "option not found: " + string(e) 27 | } 28 | -------------------------------------------------------------------------------- /option.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import "errors" 18 | 19 | // AddOption adds a new option and value to the configuration. 20 | // 21 | // If the section is nil then uses the section by default; if it does not exist, 22 | // it is created in advance. 23 | // 24 | // It returns true if the option and value were inserted, and false if the value 25 | // was overwritten. 26 | func (c *Config) AddOption(section string, option string, value string) bool { 27 | c.AddSection(section) // Make sure section exists 28 | 29 | if section == "" { 30 | section = DEFAULT_SECTION 31 | } 32 | 33 | _, ok := c.data[section][option] 34 | 35 | c.data[section][option] = &tValue{c.lastIdOption[section], value} 36 | c.lastIdOption[section]++ 37 | 38 | return !ok 39 | } 40 | 41 | // RemoveOption removes a option and value from the configuration. 42 | // It returns true if the option and value were removed, and false otherwise, 43 | // including if the section did not exist. 44 | func (c *Config) RemoveOption(section string, option string) bool { 45 | if _, ok := c.data[section]; !ok { 46 | return false 47 | } 48 | 49 | _, ok := c.data[section][option] 50 | delete(c.data[section], option) 51 | 52 | return ok 53 | } 54 | 55 | // HasOption checks if the configuration has the given option in the section. 56 | // It returns false if either the option or section do not exist. 57 | func (c *Config) HasOption(section string, option string) bool { 58 | if _, ok := c.data[section]; !ok { 59 | return false 60 | } 61 | 62 | _, okd := c.data[DEFAULT_SECTION][option] 63 | _, oknd := c.data[section][option] 64 | 65 | return okd || oknd 66 | } 67 | 68 | // Options returns the list of options available in the given section. 69 | // It returns an error if the section does not exist and an empty list if the 70 | // section is empty. Options within the default section are also included. 71 | func (c *Config) Options(section string) (options []string, err error) { 72 | if _, ok := c.data[section]; !ok { 73 | return nil, errors.New(SectionError(section).Error()) 74 | } 75 | 76 | // Keep a map of option names we've seen to deduplicate. 77 | optionMap := make(map[string]struct{}, 78 | len(c.data[DEFAULT_SECTION])+len(c.data[section])) 79 | for s, _ := range c.data[DEFAULT_SECTION] { 80 | optionMap[s] = struct{}{} 81 | } 82 | for s, _ := range c.data[section] { 83 | optionMap[s] = struct{}{} 84 | } 85 | 86 | // Get the keys. 87 | i := 0 88 | options = make([]string, len(optionMap)) 89 | for k, _ := range optionMap { 90 | options[i] = k 91 | i++ 92 | } 93 | 94 | return options, nil 95 | } 96 | 97 | // SectionOptions returns only the list of options available in the given section. 98 | // Unlike Options, SectionOptions doesn't return options in default section. 99 | // It returns an error if the section doesn't exist. 100 | func (c *Config) SectionOptions(section string) (options []string, err error) { 101 | if _, ok := c.data[section]; !ok { 102 | return nil, errors.New(SectionError(section).Error()) 103 | } 104 | 105 | options = make([]string, len(c.data[section])) 106 | i := 0 107 | for s, _ := range c.data[section] { 108 | options[i] = s 109 | i++ 110 | } 111 | 112 | return options, nil 113 | } 114 | -------------------------------------------------------------------------------- /read.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import ( 18 | "bufio" 19 | "errors" 20 | "os" 21 | "strings" 22 | "unicode" 23 | ) 24 | 25 | // _read is the base to read a file and get the configuration representation. 26 | // That representation can be queried with GetString, etc. 27 | func _read(fname string, c *Config) (*Config, error) { 28 | file, err := os.Open(fname) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | if err = c.read(bufio.NewReader(file)); err != nil { 34 | return nil, err 35 | } 36 | 37 | if err = file.Close(); err != nil { 38 | return nil, err 39 | } 40 | 41 | return c, nil 42 | } 43 | 44 | // Read reads a configuration file and returns its representation. 45 | // All arguments, except `fname`, are related to `New()` 46 | func Read(fname string, comment, separator string, preSpace, postSpace bool) (*Config, error) { 47 | return _read(fname, New(comment, separator, preSpace, postSpace)) 48 | } 49 | 50 | // ReadDefault reads a configuration file and returns its representation. 51 | // It uses values by default. 52 | func ReadDefault(fname string) (*Config, error) { 53 | return _read(fname, NewDefault()) 54 | } 55 | 56 | // * * * 57 | 58 | func (c *Config) read(buf *bufio.Reader) (err error) { 59 | var section, option string 60 | var scanner = bufio.NewScanner(buf) 61 | for scanner.Scan() { 62 | l := strings.TrimRightFunc(stripComments(scanner.Text()), unicode.IsSpace) 63 | 64 | // Switch written for readability (not performance) 65 | switch { 66 | // Empty line and comments 67 | case len(l) == 0, l[0] == '#', l[0] == ';': 68 | continue 69 | 70 | // New section. The [ must be at the start of the line 71 | case l[0] == '[' && l[len(l)-1] == ']': 72 | option = "" // reset multi-line value 73 | section = strings.TrimSpace(l[1 : len(l)-1]) 74 | c.AddSection(section) 75 | 76 | // Continuation of multi-line value 77 | // starts with whitespace, we're in a section and working on an option 78 | case section != "" && option != "" && (l[0] == ' ' || l[0] == '\t'): 79 | prev, _ := c.RawString(section, option) 80 | value := strings.TrimSpace(l) 81 | c.AddOption(section, option, prev+"\n"+value) 82 | 83 | // Other alternatives 84 | default: 85 | i := strings.IndexAny(l, "=:") 86 | 87 | switch { 88 | // Option and value 89 | case i > 0 && l[0] != ' ' && l[0] != '\t': // found an =: and it's not a multiline continuation 90 | option = strings.TrimSpace(l[0:i]) 91 | value := strings.TrimSpace(l[i+1:]) 92 | c.AddOption(section, option, value) 93 | 94 | default: 95 | return errors.New("could not parse line: " + l) 96 | } 97 | } 98 | } 99 | return scanner.Err() 100 | } 101 | -------------------------------------------------------------------------------- /section.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | // AddSection adds a new section to the configuration. 18 | // 19 | // If the section is nil then uses the section by default which it's already 20 | // created. 21 | // 22 | // It returns true if the new section was inserted, and false if the section 23 | // already existed. 24 | func (c *Config) AddSection(section string) bool { 25 | // DEFAULT_SECTION 26 | if section == "" { 27 | return false 28 | } 29 | 30 | if _, ok := c.data[section]; ok { 31 | return false 32 | } 33 | 34 | c.data[section] = make(map[string]*tValue) 35 | 36 | // Section order 37 | c.idSection[section] = c.lastIdSection 38 | c.lastIdSection++ 39 | 40 | return true 41 | } 42 | 43 | // RemoveSection removes a section from the configuration. 44 | // It returns true if the section was removed, and false if section did not exist. 45 | func (c *Config) RemoveSection(section string) bool { 46 | _, ok := c.data[section] 47 | 48 | // Default section cannot be removed. 49 | if !ok || section == DEFAULT_SECTION { 50 | return false 51 | } 52 | 53 | for o, _ := range c.data[section] { 54 | delete(c.data[section], o) // *value 55 | } 56 | delete(c.data, section) 57 | 58 | delete(c.lastIdOption, section) 59 | delete(c.idSection, section) 60 | 61 | return true 62 | } 63 | 64 | // HasSection checks if the configuration has the given section. 65 | // (The default section always exists.) 66 | func (c *Config) HasSection(section string) bool { 67 | _, ok := c.data[section] 68 | 69 | return ok 70 | } 71 | 72 | // Sections returns the list of sections in the configuration. 73 | // (The default section always exists). 74 | func (c *Config) Sections() (sections []string) { 75 | sections = make([]string, len(c.idSection)) 76 | pos := 0 // Position in sections 77 | 78 | for i := 0; i < c.lastIdSection; i++ { 79 | for section, id := range c.idSection { 80 | if id == i { 81 | sections[pos] = section 82 | pos++ 83 | } 84 | } 85 | } 86 | 87 | return sections 88 | } 89 | -------------------------------------------------------------------------------- /testdata/source.cfg: -------------------------------------------------------------------------------- 1 | one=source1 2 | two=source2 3 | three=source3 4 | four=4 5 | 6 | two_+_four=%(two)s + %(four)s 7 | 8 | [X] 9 | x.one=sourcex1 10 | x.two=sourcex2 11 | x.three=sourcex3 12 | 13 | [Y] 14 | y.one=sourcey1 15 | y.two=sourcey2 16 | y.three=sourcey3 17 | 18 | -------------------------------------------------------------------------------- /testdata/target.cfg: -------------------------------------------------------------------------------- 1 | one=1 2 | two=2 3 | three=3 4 | five=5 5 | 6 | two_+_three=%(two)s + %(three)s 7 | 8 | [X] 9 | x.one=x1 10 | x.two=x2 11 | x.three=x3 12 | x.four=x4 13 | 14 | [Y] 15 | y.one=y1 16 | y.two=y2 17 | y.three=y3 18 | y.four=y4 19 | 20 | -------------------------------------------------------------------------------- /type.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import ( 18 | "errors" 19 | "fmt" 20 | "os" 21 | "regexp" 22 | "strconv" 23 | "strings" 24 | ) 25 | 26 | // Substitutes values, calculated by callback, on matching regex 27 | func (c *Config) computeVar(beforeValue *string, regx *regexp.Regexp, headsz, tailsz int, withVar func(*string) string) (*string, error) { 28 | var i int 29 | computedVal := beforeValue 30 | for i = 0; i < _DEPTH_VALUES; i++ { // keep a sane depth 31 | 32 | vr := regx.FindStringSubmatchIndex(*computedVal) 33 | if len(vr) == 0 { 34 | break 35 | } 36 | 37 | varname := (*computedVal)[vr[headsz]:vr[headsz+1]] 38 | varVal := withVar(&varname) 39 | if varVal == "" { 40 | return &varVal, errors.New(fmt.Sprintf("Option not found: %s", varname)) 41 | } 42 | 43 | // substitute by new value and take off leading '%(' and trailing ')s' 44 | // %(foo)s => headsz=2, tailsz=2 45 | // ${foo} => headsz=2, tailsz=1 46 | newVal := (*computedVal)[0:vr[headsz]-headsz] + varVal + (*computedVal)[vr[headsz+1]+tailsz:] 47 | computedVal = &newVal 48 | } 49 | 50 | if i == _DEPTH_VALUES { 51 | retVal := "" 52 | return &retVal, 53 | fmt.Errorf("Possible cycle while unfolding variables: max depth of %d reached", _DEPTH_VALUES) 54 | } 55 | 56 | return computedVal, nil 57 | } 58 | 59 | // Bool has the same behaviour as String but converts the response to bool. 60 | // See "boolString" for string values converted to bool. 61 | func (c *Config) Bool(section string, option string) (value bool, err error) { 62 | sv, err := c.String(section, option) 63 | if err != nil { 64 | return false, err 65 | } 66 | 67 | value, ok := boolString[strings.ToLower(sv)] 68 | if !ok { 69 | return false, errors.New("could not parse bool value: " + sv) 70 | } 71 | 72 | return value, nil 73 | } 74 | 75 | // Float has the same behaviour as String but converts the response to float. 76 | func (c *Config) Float(section string, option string) (value float64, err error) { 77 | sv, err := c.String(section, option) 78 | if err == nil { 79 | value, err = strconv.ParseFloat(sv, 64) 80 | } 81 | 82 | return value, err 83 | } 84 | 85 | // Int has the same behaviour as String but converts the response to int. 86 | func (c *Config) Int(section string, option string) (value int, err error) { 87 | sv, err := c.String(section, option) 88 | if err == nil { 89 | value, err = strconv.Atoi(sv) 90 | } 91 | 92 | return value, err 93 | } 94 | 95 | // RawString gets the (raw) string value for the given option in the section. 96 | // The raw string value is not subjected to unfolding, which was illustrated in 97 | // the beginning of this documentation. 98 | // 99 | // It returns an error if either the section or the option do not exist. 100 | func (c *Config) RawString(section string, option string) (value string, err error) { 101 | if _, ok := c.data[section]; ok { 102 | if tValue, ok := c.data[section][option]; ok { 103 | return tValue.v, nil 104 | } 105 | } 106 | return c.RawStringDefault(option) 107 | } 108 | 109 | // RawStringDefault gets the (raw) string value for the given option from the 110 | // DEFAULT section. 111 | // 112 | // It returns an error if the option does not exist in the DEFAULT section. 113 | func (c *Config) RawStringDefault(option string) (value string, err error) { 114 | if tValue, ok := c.data[DEFAULT_SECTION][option]; ok { 115 | return tValue.v, nil 116 | } 117 | return "", OptionError(option) 118 | } 119 | 120 | // String gets the string value for the given option in the section. 121 | // If the value needs to be unfolded (see e.g. %(host)s example in the beginning 122 | // of this documentation), then String does this unfolding automatically, up to 123 | // _DEPTH_VALUES number of iterations. 124 | // 125 | // It returns an error if either the section or the option do not exist, or the 126 | // unfolding cycled. 127 | func (c *Config) String(section string, option string) (value string, err error) { 128 | value, err = c.RawString(section, option) 129 | if err != nil { 130 | return "", err 131 | } 132 | 133 | // % variables 134 | computedVal, err := c.computeVar(&value, varRegExp, 2, 2, func(varName *string) string { 135 | lowerVar := *varName 136 | // search variable in default section as well as current section 137 | varVal, _ := c.data[DEFAULT_SECTION][lowerVar] 138 | if _, ok := c.data[section][lowerVar]; ok { 139 | varVal = c.data[section][lowerVar] 140 | } 141 | return varVal.v 142 | }) 143 | value = *computedVal 144 | 145 | if err != nil { 146 | return value, err 147 | } 148 | 149 | // $ environment variables 150 | computedVal, err = c.computeVar(&value, envVarRegExp, 2, 1, func(varName *string) string { 151 | return os.Getenv(*varName) 152 | }) 153 | value = *computedVal 154 | return value, err 155 | } 156 | -------------------------------------------------------------------------------- /write.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The "config" Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain 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, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package config 16 | 17 | import ( 18 | "bufio" 19 | "fmt" 20 | "os" 21 | "strings" 22 | ) 23 | 24 | // WriteFile saves the configuration representation to a file. 25 | // The desired file permissions must be passed as in os.Open. The header is a 26 | // string that is saved as a comment in the first line of the file. 27 | func (c *Config) WriteFile(fname string, perm os.FileMode, header string) error { 28 | file, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | buf := bufio.NewWriter(file) 34 | if err = c.write(buf, header); err != nil { 35 | return err 36 | } 37 | buf.Flush() 38 | 39 | return file.Close() 40 | } 41 | 42 | func (c *Config) write(buf *bufio.Writer, header string) (err error) { 43 | if header != "" { 44 | // Add comment character after of each new line. 45 | if i := strings.Index(header, "\n"); i != -1 { 46 | header = strings.Replace(header, "\n", "\n"+c.comment, -1) 47 | } 48 | 49 | if _, err = buf.WriteString(c.comment + header + "\n"); err != nil { 50 | return err 51 | } 52 | } 53 | 54 | for _, orderedSection := range c.Sections() { 55 | for section, sectionMap := range c.data { 56 | if section == orderedSection { 57 | 58 | // Skip default section if empty. 59 | if section == DEFAULT_SECTION && len(sectionMap) == 0 { 60 | continue 61 | } 62 | 63 | if _, err = buf.WriteString("\n[" + section + "]\n"); err != nil { 64 | return err 65 | } 66 | 67 | // Follow the input order in options. 68 | for i := 0; i < c.lastIdOption[section]; i++ { 69 | for option, tValue := range sectionMap { 70 | 71 | if tValue.position == i { 72 | if _, err = buf.WriteString(fmt.Sprint( 73 | option, c.separator, tValue.v, "\n")); err != nil { 74 | return err 75 | } 76 | c.RemoveOption(section, option) 77 | break 78 | } 79 | } 80 | } 81 | } 82 | } 83 | } 84 | 85 | if _, err = buf.WriteString("\n"); err != nil { 86 | return err 87 | } 88 | 89 | return nil 90 | } 91 | --------------------------------------------------------------------------------