rb-konfig 0.1.0 → 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7bffadd86f96ef3163efc25608dde8cc6b13e238687d9e5b1366afcf5ee67b56
4
- data.tar.gz: 0fa8992ef19d0985253337af611418d20f8a1cbf74642879571d8c400e479cf4
3
+ metadata.gz: 1d4f1c0da5f57c267a60744219db12cf6367dbbab95f3565b80fae2b0b4b44bb
4
+ data.tar.gz: 7edcd4ef1a08f53bce1fa4df0472ad1f52edb01734af8f0ccbc7d1bac5befbfb
5
5
  SHA512:
6
- metadata.gz: 4e354c93f08eba4c21fd691fc012c01769afec1dbf931da322fee7b3e46e58fa07ab0d13004e5b1c211ebeb55647656ee02816043aee9f441b3fb3c27e80a148
7
- data.tar.gz: cbbbf864513bf6dfac4958616fd3e536962204cab81d7c1039e1832919b777f925e66dc485f3830413daabf0f24f389b2b4cb1afaef9d946110103d394219da0
6
+ metadata.gz: 7684f9dc14ff341145b701277d8e0a06fc9d11a027b1ab7d9fb707f09654510e6065bd04b25c3da12f6de51ad707b7bbae1357a659779d30d693e64d8943e53d
7
+ data.tar.gz: 24e20e5a45290d8351cf4da66b1a51fc8082b630826155db9f594907f08b457b4602e081277a4bed42937425f6074ab18ef382be9e9c23d357636ca5511200d2
@@ -1,9 +1,10 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- rb-konfig (0.1.0)
5
- activesupport
6
- hash_dot (~> 2.4)
4
+ rb-konfig (0.1.1)
5
+ activesupport (>= 4)
6
+ dry-schema (~> 1.3)
7
+ thor (~> 0.20)
7
8
 
8
9
  GEM
9
10
  remote: https://rubygems.org/
@@ -17,9 +18,38 @@ GEM
17
18
  byebug (11.0.1)
18
19
  concurrent-ruby (1.1.5)
19
20
  diff-lcs (1.3)
21
+ dry-configurable (0.8.3)
22
+ concurrent-ruby (~> 1.0)
23
+ dry-core (~> 0.4, >= 0.4.7)
24
+ dry-container (0.7.2)
25
+ concurrent-ruby (~> 1.0)
26
+ dry-configurable (~> 0.1, >= 0.1.3)
27
+ dry-core (0.4.8)
28
+ concurrent-ruby (~> 1.0)
29
+ dry-equalizer (0.2.2)
30
+ dry-inflector (0.1.2)
31
+ dry-initializer (3.0.1)
32
+ dry-logic (1.0.2)
33
+ concurrent-ruby (~> 1.0)
34
+ dry-core (~> 0.2)
35
+ dry-equalizer (~> 0.2)
36
+ dry-schema (1.3.1)
37
+ concurrent-ruby (~> 1.0)
38
+ dry-configurable (~> 0.8, >= 0.8.3)
39
+ dry-core (~> 0.4)
40
+ dry-equalizer (~> 0.2)
41
+ dry-initializer (~> 3.0)
42
+ dry-logic (~> 1.0)
43
+ dry-types (~> 1.0)
44
+ dry-types (1.1.0)
45
+ concurrent-ruby (~> 1.0)
46
+ dry-container (~> 0.3)
47
+ dry-core (~> 0.4, >= 0.4.4)
48
+ dry-equalizer (~> 0.2, >= 0.2.2)
49
+ dry-inflector (~> 0.1, >= 0.1.2)
50
+ dry-logic (~> 1.0, >= 1.0.2)
20
51
  factory_bot (5.0.2)
21
52
  activesupport (>= 4.2.0)
22
- hash_dot (2.4.1)
23
53
  i18n (1.6.0)
24
54
  concurrent-ruby (~> 1.0)
25
55
  jaro_winkler (1.5.3)
@@ -53,6 +83,7 @@ GEM
53
83
  rubocop (>= 0.71.0)
54
84
  ruby-progressbar (1.10.1)
55
85
  rufo (0.7.0)
86
+ thor (0.20.3)
56
87
  thread_safe (0.3.6)
57
88
  tzinfo (1.2.5)
58
89
  thread_safe (~> 0.1)
@@ -63,7 +94,7 @@ PLATFORMS
63
94
 
64
95
  DEPENDENCIES
65
96
  bundler (~> 2.0)
66
- byebug
97
+ byebug (~> 11.0)
67
98
  factory_bot (~> 5.0)
68
99
  rake (~> 10.0)
69
100
  rb-konfig!
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <img src="http://cdn2-cloud66-com.s3.amazonaws.com/images/oss-sponsorship.png" width=150/>
2
+
3
+ [![Codeship Status for cloud66-oss/konfig](https://app.codeship.com/projects/a8c71410-8ca4-0137-dc36-6a27a0c61ea4/status?branch=master)](https://app.codeship.com/projects/355428)
4
+
1
5
  # Konfig
2
6
 
3
7
  Konfig is a Kubernetes friendly Rails configuration file. While Rails applications can easily read YAML files to load configurations, Kubernetes is good at serving individual configuration values as files via Kubernetes Secrets. This means your Rails application needs to read the same configuration file from a YAML file in development or an individual file while running in Kubernetes. Konfig can load configuration and secrets from both YAML or folders with individual files and present them to your application the same way.
@@ -40,7 +44,8 @@ Now you can use Konfig anywhere in the code:
40
44
  puts Settings.some.configuration.value
41
45
  ```
42
46
 
43
- In `development` mode, Konfig, looks for `development.yml` in `work_dir`. In `kubernetes` mode, it looks for a file for each one of the given configuration keys. For example:
47
+ In `file` mode, Konfig, looks for any of the files specified in `default_config_files`. By default and in a non-Rails environment this will be `development.yml` and `development.local.yml` files in `work_dir`. In a Rails environment, this will be `ENVIRONMENT.yml` and `ENVIRONMENT.local.yml` files (ie `production.yml` and `production.local.yml`) files. Files added to the list later will override the values in the earlier defined files. This means, `production.local.yml` values will override `production.yml` values.
48
+ In `kubernetes` mode, it looks for a file for each one of the given configuration keys. For example:
44
49
 
45
50
  ```yml
46
51
  # development.yml
@@ -64,16 +69,21 @@ The value in `some.configuration.value` file can be `true`. Konfig tries to clea
64
69
 
65
70
  By default YAML returns `nil` for a `null` value in a YAML file. This is also replicated in directory mode.
66
71
 
72
+ ### Environment Variable Overrides
73
+
74
+ Settings can be overridden by values in environment variables. To override a value, set an environment variable that reflects the full path to the setting, replacing `.` with `_` and prefixing it with `KONFIG_`. You can change the prefix using `Konfig.configuration.env_prefix`. For example, `Settings.this.is.a.test` can be overridden with `KONFIG_THIS_IS_A_TEST`. Environment variables are not parsed for Ruby (ERB) but are coerced into the right type just like other settings.
75
+
67
76
  ### Configuration
68
77
  You can change or reach the following from `Konfig.configuration`
69
78
 
70
- `namespace`: Default is `Settings`
71
- `delimiter`: Default is `.`
72
- `default_config_file`: Default is `development.yml`
73
- `allow_nil`: Default is `true`
74
- `nil_word`: Default is `null`
75
- `mode`: No default value
76
- `workdir`: No default value
79
+ * `namespace`: Default is `Settings`
80
+ * `delimiter`: Default is `.`
81
+ * `default_config_files`: Default is [`development.yml`, `development.local.yml`]
82
+ * `allow_nil`: Default is `true`
83
+ * `nil_word`: Default is `null`
84
+ * `mode`: No default value
85
+ * `workdir`: No default value
86
+ * `schema`: Configuration validation schema. If available, the loaded, merged and parsed configuration is validated against this schema. See [Dry-Schema](https://dry-rb.org/gems/dry-schema/) for more information.
77
87
 
78
88
  ### Data types
79
89
 
@@ -84,6 +94,7 @@ The directory mode, supports the following data types in files and tries to retu
84
94
  - String
85
95
  - Date time
86
96
  - Boolean
97
+ - JSON
87
98
  - Null (see above)
88
99
 
89
100
  ### ERB
@@ -96,6 +107,26 @@ After checking out the repo, run `bin/setup` to install dependencies. You can al
96
107
 
97
108
  To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
98
109
 
110
+ ## CLI
111
+
112
+ Konfig has a CLI to generate validation schema based on a given yaml file. To generate, run:
113
+
114
+ ```bash
115
+ $ konfig gs --in sample.yml
116
+ ```
117
+
118
+ This will generate the ruby code that can be used for `Konfig.configuration.schema` like the one below:
119
+
120
+ ```ruby
121
+ Konfig.configuration.schema do
122
+ required(:some).schema do
123
+ required(:setting).filled(:string)
124
+ required(:another).filled(:integer)
125
+ required(:and_more).filled(:bool)
126
+ end
127
+ end
128
+ ```
129
+
99
130
  ## Contributing
100
131
 
101
- Bug reports and pull requests are welcome on GitHub at https://github.com/khash/konfig.
132
+ Bug reports and pull requests are welcome on GitHub at https://github.com/cloud66-oss/konfig.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative "../lib/cli.rb"
3
+
4
+ Konfig::CLI.start
@@ -6,25 +6,27 @@ Gem::Specification.new do |spec|
6
6
  spec.name = "rb-konfig"
7
7
  spec.version = Konfig::VERSION
8
8
  spec.authors = ["Khash Sajadi"]
9
- spec.email = ["khash@sajadi.co.uk"]
9
+ spec.email = ["hello@cloud66.com"]
10
10
 
11
11
  spec.summary = %q{Konfig is a Kubernetes friendly Rails configuration gem}
12
- spec.homepage = "https://github.com/khash/konfig"
12
+ spec.homepage = "https://github.com/cloud66-oss/konfig/"
13
13
 
14
14
  spec.metadata["homepage_uri"] = spec.homepage
15
- spec.metadata["source_code_uri"] = "https://github.com/khash/konfig"
15
+ spec.metadata["source_code_uri"] = "https://github.com/cloud66-oss/konfig/"
16
16
 
17
17
  # Specify which files should be added to the gem when it is released.
18
18
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
19
  spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
20
20
  `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
21
  end
22
- spec.bindir = "exe"
23
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.bindir = "bin"
23
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
24
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
24
25
  spec.require_paths = ["lib"]
25
26
 
26
- spec.add_dependency "hash_dot", "~> 2.4"
27
- spec.add_dependency "activesupport"
27
+ spec.add_dependency "activesupport", ">= 4"
28
+ spec.add_dependency "dry-schema", "~> 1.3"
29
+ spec.add_dependency "thor", "~> 0.20"
28
30
 
29
31
  spec.add_development_dependency "bundler", "~> 2.0"
30
32
  spec.add_development_dependency "rake", "~> 10.0"
@@ -33,5 +35,5 @@ Gem::Specification.new do |spec|
33
35
  spec.add_development_dependency "rubocop", "~> 0.69"
34
36
  spec.add_development_dependency "rubocop-performance", "~> 1.3"
35
37
  spec.add_development_dependency "rufo", "~> 0.7"
36
- spec.add_development_dependency "byebug"
38
+ spec.add_development_dependency "byebug", "~> 11.0"
37
39
  end
@@ -0,0 +1,19 @@
1
+ require "thor"
2
+ require "konfig"
3
+
4
+ module Konfig
5
+ class CLI < Thor
6
+ desc "gs", "Generate schema based on a given yaml file"
7
+ option :in, required: true
8
+
9
+ def gs
10
+ infile = options[:in]
11
+ workdir = File.dirname(infile)
12
+ filename = File.basename(infile)
13
+ provider = Konfig::YamlProvider.new(workdir: workdir, filename: filename)
14
+ provider.load(false)
15
+
16
+ puts Settings.generate_schema
17
+ end
18
+ end
19
+ end
@@ -1,4 +1,5 @@
1
1
  require "active_support/core_ext/hash"
2
+ require "dry-schema"
2
3
  Dir["#{File.dirname(__FILE__)}/konfig/**/*.rb"].each { |f| load(f) }
3
4
 
4
5
  module Konfig
@@ -7,23 +8,29 @@ module Konfig
7
8
  end
8
9
 
9
10
  def self.load
10
- provider = ConfigProvider.provider(mode: self.configuration.mode, workdir: self.configuration.workdir)
11
+ provider = ProviderFactory.create_provider(mode: self.configuration.mode, workdir: self.configuration.workdir)
11
12
  provider.load
12
13
  end
13
14
 
14
15
  class Config
15
16
  attr_writer :namespace
16
17
  attr_writer :delimiter
17
- attr_writer :default_config_file
18
+ attr_writer :default_config_files
18
19
  attr_writer :allow_nil
19
20
  attr_writer :nil_word
20
21
  attr_writer :mode
21
22
  attr_writer :workdir
23
+ attr_writer :env_prefix
24
+ attr_writer :logger
22
25
 
23
26
  def namespace
24
27
  @namespace || "Settings"
25
28
  end
26
29
 
30
+ def env_prefix
31
+ @env_prefix || "KONFIG"
32
+ end
33
+
27
34
  def workdir
28
35
  raise NotConfiguredError, "have you set workdir?" unless @workdir
29
36
 
@@ -36,12 +43,37 @@ module Konfig
36
43
  @mode
37
44
  end
38
45
 
46
+ def logger
47
+ @logger if @logger
48
+ if defined?(Rails) && Rails.logger
49
+ Rails.logger
50
+ else
51
+ Logger.new(STDOUT)
52
+ end
53
+ end
54
+
55
+ def schema=(value)
56
+ @schema = value
57
+ end
58
+
59
+ def schema(&block)
60
+ if block_given?
61
+ @schema = Dry::Schema.define(&block)
62
+ else
63
+ @schema
64
+ end
65
+ end
66
+
39
67
  def delimiter
40
68
  @delimiter || "."
41
69
  end
42
70
 
43
- def default_config_file
44
- @default_config_file || "development.yml"
71
+ def default_config_files
72
+ if defined?(Rails)
73
+ @default_config_files || ["#{Rails.env.downcase}.yml", "#{Rails.env.downcase}.local.yml"]
74
+ else
75
+ @default_config_files || ["development.yml", "development.local.yml"]
76
+ end
45
77
  end
46
78
 
47
79
  def allow_nil
@@ -11,18 +11,5 @@ module Konfig
11
11
  @mode = mode
12
12
  @workdir = workdir
13
13
  end
14
-
15
- def self.provider(mode:, workdir:)
16
- raise ArgumentError unless workdir
17
- raise ArgumentError unless [:yaml, :directory].include? mode
18
-
19
- if mode == :yaml
20
- return YamlProvider.new(workdir: workdir)
21
- elsif mode == :directory
22
- return DirectoryProvider.new(workdir: workdir)
23
- else
24
- raise ArgumentError
25
- end
26
- end
27
14
  end
28
15
  end
@@ -1,48 +1,28 @@
1
1
  require_relative "config_provider"
2
2
  require "date"
3
+ require "json"
3
4
 
4
5
  module Konfig
5
- class NilClass; end
6
-
7
- NIL_VALUE = NilClass.new
8
-
9
6
  class DirectoryProvider < ConfigProvider
10
7
  def initialize(workdir:)
11
8
  super(mode: :yaml, workdir: workdir)
12
9
  @files = Dir.children(@workdir)
10
+ # exclude any directories there
11
+ @files = @files.delete_if { |x| File.directory?(File.join(@workdir, x)) }
13
12
  end
14
13
 
15
14
  def load
15
+ Konfig.configuration.logger.info "Loading files from #{@workdir}"
16
16
  build_object_from_list(@files)
17
17
  end
18
18
 
19
19
  private
20
20
 
21
- # deserializers. order matters here
22
- DESERIALIZERS = [
23
- lambda { |value| Integer(value) rescue NIL_VALUE }, # integer
24
- lambda { |value| Float(value) rescue NIL_VALUE }, # float
25
- lambda { |value| (["true", "false"].include?(value)) ? (value == "true") : NIL_VALUE }, # boolean
26
- lambda { |value| DateTime.parse(value) rescue NIL_VALUE }, # date time
27
- lambda { |value| (value == Konfig.configuration.nil_word && Konfig.configuration.allow_nil) ? nil : NIL_VALUE }, # nil value
28
- lambda { |value| value }, # string. should always be the last one
29
- ]
30
-
31
21
  def get_value(filepath)
32
22
  fullpath = File.join(@workdir, filepath)
33
23
  raise FileNotFound, "key #{filepath} not found. Expecting to find it in #{fullpath}" unless File.exist? fullpath
34
24
  content = File.read(fullpath).chomp
35
- return coerce(content)
36
- end
37
-
38
- def coerce(value)
39
- # assume a float first
40
- DESERIALIZERS.each do |deseralizer|
41
- result = deseralizer.call(value)
42
- return result unless result == NIL_VALUE
43
- end
44
-
45
- raise UnsupportedValueType, "'#{value}' is unsupported type"
25
+ return Konfig::Utils.coerce(content)
46
26
  end
47
27
 
48
28
  def build_hash_from_list(list)
@@ -64,7 +44,10 @@ module Konfig
64
44
  full_hash.deep_merge!(item)
65
45
  end
66
46
 
67
- Object.const_set(Konfig.configuration.namespace, full_hash.to_dot)
47
+ full_hash = Konfig::EnvReplacer.replace(full_hash)
48
+ os = Konfig::Option.new
49
+ full_hash = os.load(full_hash)
50
+ Object.const_set(Konfig.configuration.namespace, full_hash)
68
51
  end
69
52
 
70
53
  def build_hash(key, value)
@@ -0,0 +1,31 @@
1
+ module Konfig
2
+ class EnvReplacer
3
+ def self.replace(h)
4
+ return iterate(h)
5
+ end
6
+
7
+ private
8
+
9
+ def self.iterate(h, keychain = "")
10
+ h.each_with_object({}) { |(k, v), g|
11
+ chain = "#{keychain.upcase}_#{k.to_s.upcase}"
12
+ if Hash === v
13
+ g[k] = self.iterate(v, chain)
14
+ else
15
+ g[k] = self.get_env(chain, v, g)
16
+ end
17
+ }
18
+ end
19
+
20
+ def self.get_env(key, value, obj)
21
+ raise InvalidSettingNameError if key.length <= 1
22
+
23
+ env_key = "#{Konfig.configuration.env_prefix}_#{key[1..-1]}"
24
+ if ENV.has_key? env_key
25
+ return Konfig::Utils.coerce(ENV[env_key])
26
+ else
27
+ return value
28
+ end
29
+ end
30
+ end
31
+ end
@@ -2,4 +2,15 @@ module Konfig
2
2
  class Error < StandardError; end
3
3
  class FileNotFound < Error; end
4
4
  class NotConfiguredError < Error; end
5
+ class InvalidSettingName < Error; end
6
+ class KeyError < Error; end
7
+ class FileError < Error; end
8
+
9
+ class ValidationError < Error
10
+ def self.format(v_res)
11
+ v_res.errors.group_by(&:path).map do |path, messages|
12
+ "#{" " * 2}#{path.join(".")}: #{messages.map(&:text).join("; ")}"
13
+ end.join("\n")
14
+ end
15
+ end
5
16
  end
@@ -0,0 +1,113 @@
1
+ require "ostruct"
2
+
3
+ module Konfig
4
+ class Option < OpenStruct
5
+ include Enumerable
6
+
7
+ def keys
8
+ marshal_dump.keys
9
+ end
10
+
11
+ def empty?
12
+ marshal_dump.empty?
13
+ end
14
+
15
+ def load(h)
16
+ marshal_load(__convert(h).marshal_dump)
17
+ validate!
18
+ self
19
+ end
20
+
21
+ def key?(key)
22
+ table.key?(key)
23
+ end
24
+
25
+ def has_key?(key)
26
+ table.has_key?(key)
27
+ end
28
+
29
+ def validate!
30
+ if Konfig.configuration.schema
31
+ v_res = Konfig.configuration.schema.(self.marshal_dump)
32
+
33
+ unless v_res.success?
34
+ error = Konfig::ValidationError.format(v_res)
35
+ raise Konfig::ValidationError.new("Config validation failed:\n\n#{error}")
36
+ end
37
+ end
38
+ end
39
+
40
+ SETTINGS_RESERVED_NAMES = %w[select collect test count zip min max].freeze
41
+
42
+ SETTINGS_RESERVED_NAMES.each do |name|
43
+ define_method name do
44
+ self[name]
45
+ end
46
+ end
47
+
48
+ def [](param)
49
+ return super if SETTINGS_RESERVED_NAMES.include?(param)
50
+ send("#{param}")
51
+ end
52
+
53
+ def []=(param, value)
54
+ send("#{param}=", value)
55
+ end
56
+
57
+ def method_missing(method_name, *args)
58
+ raise KeyError, "key not found: #{method_name.inspect}" unless key?(method_name) if method_name !~ /.*(?==\z)/m
59
+
60
+ super
61
+ end
62
+
63
+ def respond_to_missing?(*args)
64
+ super
65
+ end
66
+
67
+ def generate_schema(start = nil)
68
+ start = self if start.nil?
69
+ result = []
70
+ start.table.each do |k, v|
71
+ if v.is_a?(Option)
72
+ result << "required(:#{k}).schema do"
73
+ result << generate_schema(v)
74
+ result << "end"
75
+ elsif [String, Integer, Numeric, Array].include? v.class
76
+ result << generate_required(k, v)
77
+ elsif [TrueClass, FalseClass].include? v.class
78
+ result << "required(:#{k}).filled(:bool)"
79
+ elsif v.nil?
80
+ result << "required(:#{k})"
81
+ end
82
+ end
83
+
84
+ return result
85
+ end
86
+
87
+ protected
88
+
89
+ def __convert(h)
90
+ s = self.class.new
91
+
92
+ h.each do |k, v|
93
+ k = k.to_s if !k.respond_to?(:to_sym) && k.respond_to?(:to_s)
94
+ s.new_ostruct_member(k)
95
+
96
+ if v.is_a?(Hash)
97
+ v = v["type"] == "hash" ? v["contents"] : __convert(v)
98
+ elsif v.is_a?(Array)
99
+ v = v.collect { |e| e.instance_of?(Hash) ? __convert(e) : e }
100
+ end
101
+
102
+ s.send("#{k}=".to_sym, v)
103
+ end
104
+ s
105
+ end
106
+
107
+ private
108
+
109
+ def generate_required(k, v)
110
+ "required(:#{k}).filled(:#{v.class.name.downcase})"
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,16 @@
1
+ module Konfig
2
+ class ProviderFactory
3
+ def self.create_provider(mode:, workdir:)
4
+ raise ArgumentError unless workdir
5
+ raise ArgumentError unless [:yaml, :directory].include? mode
6
+
7
+ if mode == :yaml
8
+ return YamlProvider.new(workdir: workdir)
9
+ elsif mode == :directory
10
+ return DirectoryProvider.new(workdir: workdir)
11
+ else
12
+ raise ArgumentError
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,40 @@
1
+ module Konfig
2
+ class NilClass; end
3
+
4
+ NIL_VALUE = NilClass.new
5
+
6
+ private
7
+
8
+ # deserializers. order matters here
9
+ DESERIALIZERS = [
10
+ lambda { |value| Integer(value) rescue NIL_VALUE }, # integer
11
+ lambda { |value| Float(value) rescue NIL_VALUE }, # float
12
+ lambda { |value| (["true", "false"].include?(value)) ? (value == "true") : NIL_VALUE }, # boolean
13
+ lambda { |value| DateTime.parse(value) rescue NIL_VALUE }, # date time
14
+ lambda { |value| (value == Konfig.configuration.nil_word && Konfig.configuration.allow_nil) ? nil : NIL_VALUE }, # nil value
15
+ lambda do |value|
16
+ result = JSON.parse(value, { symbolize_names: true })
17
+ if result == nil && !Konfig.configuration.allow_nil
18
+ return NIL_VALUE
19
+ else
20
+ result
21
+ end
22
+ rescue
23
+ NIL_VALUE
24
+ end, # json
25
+ lambda { |value| value }, # string. should always be the last one
26
+ ]
27
+
28
+ class Utils
29
+ # coreces the given value (string) into the best possible type
30
+ def self.coerce(value)
31
+ # assume a float first
32
+ DESERIALIZERS.each do |deseralizer|
33
+ result = deseralizer.call(value)
34
+ return result unless result == NIL_VALUE
35
+ end
36
+
37
+ raise UnsupportedValueType, "'#{value}' is unsupported type"
38
+ end
39
+ end
40
+ end
@@ -1,3 +1,3 @@
1
1
  module Konfig
2
- VERSION ||= "0.1.0"
2
+ VERSION ||= "0.1.1"
3
3
  end
@@ -1,28 +1,44 @@
1
1
  require_relative "config_provider"
2
2
  require "yaml"
3
- require "hash_dot"
3
+ require "ostruct"
4
4
  require "erb"
5
5
 
6
6
  module Konfig
7
7
  class YamlProvider < ConfigProvider
8
- attr_reader :file
8
+ attr_reader :files
9
9
  attr_reader :raw_settings
10
10
 
11
- def initialize(workdir:, filename: Konfig.configuration.default_config_file)
11
+ def initialize(workdir:, filenames: Konfig.configuration.default_config_files)
12
12
  super(mode: :yaml, workdir: workdir)
13
- @file = File.join(workdir, filename)
14
- raise FileNotFound, "#{@file} not found" unless File.exists? @file
13
+ @files = filenames.map { |f| File.join(workdir, f) }
14
+ raise FileNotFound, "none of the configuration files (#{@files}) found" if @files.all? { |f| !File.exists?(f) }
15
15
  end
16
16
 
17
- def load
18
- content = YAML.load(ERB.new(IO.read(@file)).result) if @file and File.exist?(@file)
19
- content ||= {}
17
+ def load(parse = true)
18
+ content = {}
19
+ @files.each do |f|
20
+ # since we've looked for file existence before, we can skip any that's missing
21
+ next if !File.exists?(f)
22
+ Konfig.configuration.logger.info "Loading #{f}"
23
+ file_content = IO.read(f)
24
+ raise FileError, "file #{f} is empty" if file_content.blank?
20
25
 
21
- @raw_settings = content.to_dot
26
+ yaml_content = parse ? ERB.new(file_content).result : file_content
27
+ raise FileError, "#{f} seems empty" unless yaml_content
28
+ parsed = YAML.load(yaml_content)
29
+ raise FileError, "#{f} cannot be loaded as YAML" unless parsed
30
+ current_content = parsed.deep_symbolize_keys if f and File.exist?(f)
31
+ current_content = Konfig::EnvReplacer.replace(current_content)
32
+
33
+ content = content.deep_merge(current_content)
34
+ end
35
+
36
+ os = Konfig::Option.new
37
+ @raw_settings = os.load(content)
22
38
  Object.send(:remove_const, Konfig.configuration.namespace) if Object.const_defined?(Konfig.configuration.namespace)
23
39
  Object.const_set(Konfig.configuration.namespace, @raw_settings)
24
40
  rescue Psych::SyntaxError => exc
25
- raise "YAML syntax error occurred while parsing #{@file}. " \
41
+ raise "YAML syntax error occurred while parsing #{f}. " \
26
42
  "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
27
43
  "Error: #{exc.message}"
28
44
  end
metadata CHANGED
@@ -1,43 +1,57 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rb-konfig
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Khash Sajadi
8
8
  autorequire:
9
- bindir: exe
9
+ bindir: bin
10
10
  cert_chain: []
11
- date: 2019-06-27 00:00:00.000000000 Z
11
+ date: 2019-08-21 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
- name: hash_dot
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '4'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '4'
27
+ - !ruby/object:Gem::Dependency
28
+ name: dry-schema
15
29
  requirement: !ruby/object:Gem::Requirement
16
30
  requirements:
17
31
  - - "~>"
18
32
  - !ruby/object:Gem::Version
19
- version: '2.4'
33
+ version: '1.3'
20
34
  type: :runtime
21
35
  prerelease: false
22
36
  version_requirements: !ruby/object:Gem::Requirement
23
37
  requirements:
24
38
  - - "~>"
25
39
  - !ruby/object:Gem::Version
26
- version: '2.4'
40
+ version: '1.3'
27
41
  - !ruby/object:Gem::Dependency
28
- name: activesupport
42
+ name: thor
29
43
  requirement: !ruby/object:Gem::Requirement
30
44
  requirements:
31
- - - ">="
45
+ - - "~>"
32
46
  - !ruby/object:Gem::Version
33
- version: '0'
47
+ version: '0.20'
34
48
  type: :runtime
35
49
  prerelease: false
36
50
  version_requirements: !ruby/object:Gem::Requirement
37
51
  requirements:
38
- - - ">="
52
+ - - "~>"
39
53
  - !ruby/object:Gem::Version
40
- version: '0'
54
+ version: '0.20'
41
55
  - !ruby/object:Gem::Dependency
42
56
  name: bundler
43
57
  requirement: !ruby/object:Gem::Requirement
@@ -140,20 +154,23 @@ dependencies:
140
154
  name: byebug
141
155
  requirement: !ruby/object:Gem::Requirement
142
156
  requirements:
143
- - - ">="
157
+ - - "~>"
144
158
  - !ruby/object:Gem::Version
145
- version: '0'
159
+ version: '11.0'
146
160
  type: :development
147
161
  prerelease: false
148
162
  version_requirements: !ruby/object:Gem::Requirement
149
163
  requirements:
150
- - - ">="
164
+ - - "~>"
151
165
  - !ruby/object:Gem::Version
152
- version: '0'
166
+ version: '11.0'
153
167
  description:
154
168
  email:
155
- - khash@sajadi.co.uk
156
- executables: []
169
+ - hello@cloud66.com
170
+ executables:
171
+ - console
172
+ - konfig
173
+ - setup
157
174
  extensions: []
158
175
  extra_rdoc_files: []
159
176
  files:
@@ -164,22 +181,29 @@ files:
164
181
  - ".ruby-version"
165
182
  - Gemfile
166
183
  - Gemfile.lock
184
+ - LICENSE
167
185
  - README.md
168
186
  - Rakefile
169
187
  - bin/console
188
+ - bin/konfig
170
189
  - bin/setup
171
190
  - konfig.gemspec
191
+ - lib/cli.rb
172
192
  - lib/konfig.rb
173
193
  - lib/konfig/config_provider.rb
174
194
  - lib/konfig/directory_provider.rb
195
+ - lib/konfig/env_replacer.rb
175
196
  - lib/konfig/errors.rb
197
+ - lib/konfig/option.rb
198
+ - lib/konfig/provider_factory.rb
199
+ - lib/konfig/utils.rb
176
200
  - lib/konfig/version.rb
177
201
  - lib/konfig/yaml_provider.rb
178
- homepage: https://github.com/khash/konfig
202
+ homepage: https://github.com/cloud66-oss/konfig/
179
203
  licenses: []
180
204
  metadata:
181
- homepage_uri: https://github.com/khash/konfig
182
- source_code_uri: https://github.com/khash/konfig
205
+ homepage_uri: https://github.com/cloud66-oss/konfig/
206
+ source_code_uri: https://github.com/cloud66-oss/konfig/
183
207
  post_install_message:
184
208
  rdoc_options: []
185
209
  require_paths: