nero 0.6.0 → 0.7.0.rc3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.envrc +3 -1
- data/.irbrc +4 -0
- data/CHANGELOG.md +73 -1
- data/README.md +229 -165
- data/UPGRADING.md +255 -0
- data/_irbrc.example +4 -0
- data/lib/nero/base_tag.rb +9 -0
- data/lib/nero/context.rb +31 -0
- data/lib/nero/deferred.rb +9 -0
- data/lib/nero/env_tag.rb +46 -0
- data/lib/nero/error.rb +22 -0
- data/lib/nero/format_tag.rb +17 -0
- data/lib/nero/ip_tag.rb +31 -0
- data/lib/nero/parser.rb +202 -0
- data/lib/nero/proc_tag.rb +9 -0
- data/lib/nero/rails/credentials_tag.rb +27 -0
- data/lib/nero/rails/duration_tag.rb +26 -0
- data/lib/nero/rails/string_inquirer_tag.rb +16 -0
- data/lib/nero/rails.rb +41 -0
- data/lib/nero/railtie.rb +4 -5
- data/lib/nero/ref.rb +10 -0
- data/lib/nero/ref_tag.rb +14 -0
- data/lib/nero/result.rb +21 -0
- data/lib/nero/root_path_tag.rb +62 -0
- data/lib/nero/version.rb +1 -1
- data/lib/nero/visitor.rb +63 -0
- data/lib/nero.rb +57 -566
- data/mise.toml +9 -0
- data/rakelib/gem.rake +4 -10
- data/tmp/.keep +0 -0
- metadata +43 -42
- data/Appraisals +0 -7
- data/gemfiles/psych_3.gemfile +0 -10
- data/gemfiles/psych_4.gemfile +0 -10
- data/lib/nero/util.rb +0 -29
data/UPGRADING.md
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# Upgrading from 0.6 to 0.7
|
|
2
|
+
|
|
3
|
+
0.7 is a rewrite. Most changes fail loudly (a `NoMethodError` or a `Nero::ParseError` at
|
|
4
|
+
boot), but a few change values **silently**. Those come first.
|
|
5
|
+
|
|
6
|
+
Deprecated usage keeps working until 0.8 and prints a warning on stderr:
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
[nero] DEPRECATION WARNING: !env/integer? is deprecated and will be removed in 0.8 (use !env?/integer)
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Run your app or test suite once after upgrading and fix every warning.
|
|
13
|
+
|
|
14
|
+
## Checklist
|
|
15
|
+
|
|
16
|
+
- [ ] Ruby ≥ 3.3
|
|
17
|
+
- [ ] [Keys](#1-neroload-returns-string-keys): `Nero.load`/`load_file` return **string** keys
|
|
18
|
+
- [ ] [Booleans](#2-booleans): `!env/bool` is strict, optional bools are `nil` when missing
|
|
19
|
+
- [ ] [Errors](#3-errors): rescue `Nero::ParseError`
|
|
20
|
+
- [ ] [Configuration](#4-neroconfigure-is-gone): no more `Nero.configure`
|
|
21
|
+
- [ ] [`load_config`](#5-load_config-is-gone) → `config_for`
|
|
22
|
+
- [ ] [Tags](#6-tags): `!ref`, `!str/format`, optional env tags, `!path`, `!uri`
|
|
23
|
+
- [ ] [Custom tags](#7-custom-tags): new API
|
|
24
|
+
- [ ] [Loading Ruby objects](#8-loading-ruby-objects): `extra_permitted_classes:` → `permitted_classes:`
|
|
25
|
+
- [ ] [`NERO_ENV_ALL_OPTIONAL`](#9-nero_env_all_optional) → `NERO_ALL_OPTIONAL`
|
|
26
|
+
|
|
27
|
+
A good way to verify the upgrade: dump your config with 0.6 and with 0.7, per environment,
|
|
28
|
+
and compare.
|
|
29
|
+
|
|
30
|
+
```shell
|
|
31
|
+
$ bin/rails runner 'puts AppConfig.config.to_json' > before.json # on 0.6
|
|
32
|
+
$ bin/rails runner 'puts AppConfig.config.to_json' > after.json # on 0.7
|
|
33
|
+
$ diff <(jq -S . before.json) <(jq -S . after.json)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## 1. `Nero.load` returns string keys
|
|
37
|
+
|
|
38
|
+
**Silent.** `Nero.load` and `Nero.load_file` now behave like `YAML.load`/`YAML.load_file`:
|
|
39
|
+
keys are strings. In 0.6 they were symbols. Code like `config[:host]` gets `nil` without an
|
|
40
|
+
error.
|
|
41
|
+
|
|
42
|
+
```ruby
|
|
43
|
+
# 0.6
|
|
44
|
+
Nero.load_file("config/app.yml", root: :production)[:host]
|
|
45
|
+
|
|
46
|
+
# 0.7: either ask for symbols...
|
|
47
|
+
Nero.load_file("config/app.yml", root: :production, symbolize_names: true)[:host]
|
|
48
|
+
# ...or use string keys
|
|
49
|
+
Nero.load_file("config/app.yml", root: :production)["host"]
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`Nero.config_for` still returns symbol keys, like Rails' `config_for`:
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
Nero.config_for(:app, env: :production)[:host]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Results are plain Hashes: `Nero::Config` and its `dig!` are gone. Use `dig` or `fetch`.
|
|
59
|
+
|
|
60
|
+
`root:` accepts a symbol or a string (`root: :production` finds the key `production`).
|
|
61
|
+
`load_file` and `config_for` also accept `env:` as an alias.
|
|
62
|
+
|
|
63
|
+
## 2. Booleans
|
|
64
|
+
|
|
65
|
+
**Silent.** Two changes:
|
|
66
|
+
|
|
67
|
+
1. **`!env/bool` is strict.** Only `1/y/yes/true/on` and `0/n/no/false/off` are accepted
|
|
68
|
+
(case-insensitive, surrounding whitespace ignored). Anything else, including an empty
|
|
69
|
+
value, is a parse error. 0.6 matched without anchors, so any value containing a `y` (like
|
|
70
|
+
`maybe`) was `true`, and `FEATURE=n`-style typos could turn a feature on. Check the values
|
|
71
|
+
you set in your environments.
|
|
72
|
+
2. **A missing optional bool is `nil`** (0.6: `false`). Missing is not the same as "no". If
|
|
73
|
+
your code relies on `false`, give it a fallback:
|
|
74
|
+
|
|
75
|
+
```yaml
|
|
76
|
+
# 0.6
|
|
77
|
+
debug: !env/bool? DEBUG # false when DEBUG is not set
|
|
78
|
+
# 0.7
|
|
79
|
+
debug: !env/bool [DEBUG, false] # false when DEBUG is not set
|
|
80
|
+
debug: !env?/bool DEBUG # nil when DEBUG is not set
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## 3. Errors
|
|
84
|
+
|
|
85
|
+
0.6 raised on the first problem, with a class depending on what went wrong (`KeyError` for a
|
|
86
|
+
missing env var, `RuntimeError` for a bad boolean, ...). 0.7 collects **all** problems and
|
|
87
|
+
raises one `Nero::ParseError`:
|
|
88
|
+
|
|
89
|
+
```ruby
|
|
90
|
+
Nero.load("a: !env A\nb: !env B", environ: {})
|
|
91
|
+
# => Nero::ParseError: environment variable A is not set, environment variable B is not set
|
|
92
|
+
|
|
93
|
+
rescue Nero::ParseError => e
|
|
94
|
+
e.errors.map(&:message)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Update specs and rescues that expect `KeyError`. Note that `Nero::Error` is now the class of
|
|
98
|
+
a single error message, not an exception: `rescue Nero::Error` no longer catches anything.
|
|
99
|
+
|
|
100
|
+
Need the errors without an exception? Use the parser directly:
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
result = Nero::Parser.new(root: :production).parse_file("config/app.yml")
|
|
104
|
+
result.ok? # => false
|
|
105
|
+
result.errors # => [#<Nero::Error ...>, ...]
|
|
106
|
+
result.warnings # => deprecation warnings
|
|
107
|
+
result.value! # => the config, or raises Nero::ParseError
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## 4. `Nero.configure` is gone
|
|
111
|
+
|
|
112
|
+
There is no global configuration anymore. Pass custom tags in a block to `load`,
|
|
113
|
+
`load_file` or `config_for`:
|
|
114
|
+
|
|
115
|
+
```ruby
|
|
116
|
+
# 0.6
|
|
117
|
+
Nero.configure do |nero|
|
|
118
|
+
nero.config_dir = "config"
|
|
119
|
+
nero.add_tag("upcase") { |tag| tag.args.join.upcase }
|
|
120
|
+
end
|
|
121
|
+
Nero.config_for(:app)
|
|
122
|
+
|
|
123
|
+
# 0.7
|
|
124
|
+
Nero.config_for(:app) do |nero|
|
|
125
|
+
nero.add_tag("upcase", ->(args, **) { args.join.upcase })
|
|
126
|
+
end
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
If you load config in several places, wrap the block in a method of your own.
|
|
130
|
+
|
|
131
|
+
**`config_dir`**: `Nero.config_for(:app)` reads `config/app.yml` from the current directory,
|
|
132
|
+
or `Rails.root/config/app.yml` in a Rails app (so no setting is needed there). For another
|
|
133
|
+
directory, pass a `Pathname` (`Nero.config_for(Pathname("etc/app.yml"))`) or override
|
|
134
|
+
`Nero.config_dir`:
|
|
135
|
+
|
|
136
|
+
```ruby
|
|
137
|
+
def Nero.config_dir = Pathname("etc").expand_path
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## 5. `load_config` is gone
|
|
141
|
+
|
|
142
|
+
It was deprecated in 0.6. Use `config_for` (symbol keys) or `load_file` (string keys):
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
# 0.6
|
|
146
|
+
Nero.load_config(:app, root: Rails.env)
|
|
147
|
+
# 0.7
|
|
148
|
+
Nero.config_for(:app, env: Rails.env) # env: defaults to Rails.env in a Rails app
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## 6. Tags
|
|
152
|
+
|
|
153
|
+
| 0.6 | 0.7 | |
|
|
154
|
+
|---|---|---|
|
|
155
|
+
| `!env/integer? PORT` | `!env?/integer PORT` | Same for `float`, `bool`, `path`: the `?` moved to `env?`. The old names warn until 0.8. |
|
|
156
|
+
| `!ref [db, host]` | `!ref db.host` | The sequence form warns until 0.8. |
|
|
157
|
+
| `!str/format {fmt: "%<x>s", x: 1}` | `!format ["%<x>s", x: 1]` | The map form with `fmt:` is gone. Positional args (`!format ["%s/x", !ref url]`) still work. `!str/format` stays as an alias. |
|
|
158
|
+
| `!path [a, b]` | `!path/git_root [a, b]`, `!env/path VAR` | `!path` is gone: it built a path relative to the current directory. Use a root-relative path, or a path from the environment. |
|
|
159
|
+
| `!uri [smtps://, !env CREDS, @host]` | `!format ["smtps://%s@host", !env CREDS]` | `!uri` is gone: it concatenated and parsed without escaping. Build the string, and call `URI()` in Ruby if you need an object. |
|
|
160
|
+
| `!path/rails_root` | `!path/rails_root` | Now only available in a Rails app. `!path/git_root` works everywhere. |
|
|
161
|
+
|
|
162
|
+
New: `!env/int`, `!env/boolean` (aliases), `!env/path` and `!env?/path`, `!format`; with
|
|
163
|
+
Rails also `!credentials`, `!duration` and `!str/inquirer`.
|
|
164
|
+
|
|
165
|
+
## 7. Custom tags
|
|
166
|
+
|
|
167
|
+
Tags no longer read `tag.args`/`coder`/`ctx`. A tag is anything that responds to
|
|
168
|
+
`resolve(args, context:)`.
|
|
169
|
+
|
|
170
|
+
`args` is an Array (scalar or sequence in YAML) or a Hash (mapping). Nested tags are already
|
|
171
|
+
resolved. Keys in a mapping follow the entry point: strings with `load`/`load_file`, symbols
|
|
172
|
+
with `config_for` or `symbolize_names: true`. 0.6 always gave symbols, so a tag that reads
|
|
173
|
+
`args[:key]` should handle both, e.g. `args.transform_keys(&:to_sym)`.
|
|
174
|
+
|
|
175
|
+
**A lambda** (was: a block):
|
|
176
|
+
|
|
177
|
+
```ruby
|
|
178
|
+
# 0.6
|
|
179
|
+
nero.add_tag("upcase") { |tag| tag.args.join.upcase }
|
|
180
|
+
# 0.7
|
|
181
|
+
nero.add_tag("upcase", ->(args, **) { args.join.upcase })
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
**A class** (was: `klass:` with `init_options`):
|
|
185
|
+
|
|
186
|
+
```ruby
|
|
187
|
+
# 0.6
|
|
188
|
+
class RotTag < Nero::BaseTag
|
|
189
|
+
def init_options(n: 13) = super
|
|
190
|
+
def resolve(**) = args.join.tr(...) # using options[:n]
|
|
191
|
+
end
|
|
192
|
+
nero.add_tag("rot/13", klass: RotTag[n: 13])
|
|
193
|
+
|
|
194
|
+
# 0.7
|
|
195
|
+
class RotTag < Nero::BaseTag
|
|
196
|
+
def initialize(n: 13) = @n = n
|
|
197
|
+
|
|
198
|
+
def resolve(args, context:)
|
|
199
|
+
return context.add_error("!rot needs a string") && nil unless args.first.is_a?(String)
|
|
200
|
+
args.first.tr(...) # using @n
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
nero.add_tag("rot/13", RotTag.new(n: 13))
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Report problems with `context.add_error(message)` and return `nil` instead of raising: they
|
|
207
|
+
end up in the `Nero::ParseError` together with all other errors. `context` also gives you
|
|
208
|
+
`environ` (the env vars, injectable via `environ:`), `dir` (the directory of the YAML file)
|
|
209
|
+
and `deprecate(...)`.
|
|
210
|
+
|
|
211
|
+
Built-in tag classes take their options in the constructor too:
|
|
212
|
+
|
|
213
|
+
```ruby
|
|
214
|
+
# 0.6
|
|
215
|
+
nero.add_tag("path/project_root", klass: Nero::PathRootTag[containing: ".git"])
|
|
216
|
+
nero.add_tag("env/upcase", klass: Nero::EnvTag[coerce: :upcase])
|
|
217
|
+
# 0.7
|
|
218
|
+
nero.add_tag("path/project_root", Nero::RootPathTag.new(containing: ".git"))
|
|
219
|
+
nero.add_tag("env/upcase", Nero::EnvTag.new(coerce: ->(v) { v.upcase }))
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The 0.6 post-processing block on `add_tag("x", klass: ...) { |value| ... }` is gone: wrap the
|
|
223
|
+
tag in a class or lambda instead.
|
|
224
|
+
|
|
225
|
+
`Nero::Util` (`deep_symbolize_keys`, `deep_transform_values`) is gone too.
|
|
226
|
+
|
|
227
|
+
## 8. Loading Ruby objects
|
|
228
|
+
|
|
229
|
+
Like `YAML.load`, `load`/`load_file` only instantiate `Symbol`; `config_for` also allows
|
|
230
|
+
`Date` and `Time`. Anything else (e.g. `!ruby/object:...`) is a parse error. The option to
|
|
231
|
+
allow more is now called `permitted_classes:` and **replaces** the default list, as in Psych:
|
|
232
|
+
|
|
233
|
+
```ruby
|
|
234
|
+
# 0.6
|
|
235
|
+
Nero.load(yaml, extra_permitted_classes: [Date])
|
|
236
|
+
# 0.7
|
|
237
|
+
Nero.load(yaml, permitted_classes: %w[Symbol Date])
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Aliases (`&anchor`/`*alias`, `<<:` merge keys) work as before.
|
|
241
|
+
|
|
242
|
+
## 9. `NERO_ENV_ALL_OPTIONAL`
|
|
243
|
+
|
|
244
|
+
Renamed to `NERO_ALL_OPTIONAL`, because it now also makes Rails `!credentials` optional. The
|
|
245
|
+
old name works until 0.8, with a warning. Only a non-empty value switches it on.
|
|
246
|
+
|
|
247
|
+
```shell
|
|
248
|
+
$ NERO_ALL_OPTIONAL=1 SECRET_KEY_BASE_DUMMY=1 bin/rails assets:precompile
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Per call: `Nero.load(yaml, all_optional: true)`.
|
|
252
|
+
|
|
253
|
+
## Ruby
|
|
254
|
+
|
|
255
|
+
0.7 requires Ruby 3.3 or later.
|
data/_irbrc.example
ADDED
data/lib/nero/context.rb
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
class Context
|
|
5
|
+
attr_reader :environ, :dir, :errors, :warnings
|
|
6
|
+
|
|
7
|
+
def initialize(environ:, dir: nil, all_optional: false)
|
|
8
|
+
@environ = environ
|
|
9
|
+
@dir = dir || File.realpath(".")
|
|
10
|
+
@all_optional = all_optional
|
|
11
|
+
@errors = []
|
|
12
|
+
@warnings = Set.new
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# True when missing values (env vars, credentials) resolve to nil instead of
|
|
16
|
+
# being an error. See Parser#initialize (all_optional:).
|
|
17
|
+
def all_optional? = @all_optional
|
|
18
|
+
|
|
19
|
+
def add_error(message)
|
|
20
|
+
@errors << Error.new(message)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def add_warning(message)
|
|
24
|
+
@warnings << message
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def deprecate(msg, use: nil, removed_in: "1.0")
|
|
28
|
+
add_warning "DEPRECATION WARNING: #{msg} and will be removed in #{removed_in} (use #{use})"
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
data/lib/nero/env_tag.rb
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
class EnvTag < BaseTag
|
|
5
|
+
def initialize(coerce: nil, optional: false, deprecated: nil)
|
|
6
|
+
@deprecated = deprecated
|
|
7
|
+
@coerce = coerce
|
|
8
|
+
@optional = optional
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def deprecated? = !!@deprecated
|
|
12
|
+
|
|
13
|
+
def resolve(args, context:)
|
|
14
|
+
if (msg, opts = @deprecated)
|
|
15
|
+
context.deprecate(msg, **opts)
|
|
16
|
+
end
|
|
17
|
+
var_name = args[0]
|
|
18
|
+
default = args[1]
|
|
19
|
+
|
|
20
|
+
if var_name.nil?
|
|
21
|
+
context.add_error("!env tags require a var_name, e.g. `!env FOO`, or `!env [FOO, fallback]`")
|
|
22
|
+
return
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
raw = context.environ[var_name]
|
|
26
|
+
|
|
27
|
+
if raw.nil? && default.nil?
|
|
28
|
+
context.add_error("environment variable #{var_name} is not set") unless @optional || context.all_optional?
|
|
29
|
+
return
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# A fallback is a string like an env value. For coercing tags a sequence is passed as is,
|
|
33
|
+
# so !env/list [X, [a, b]] works (other coercions report it as an error).
|
|
34
|
+
value = raw || ((default.is_a?(Array) && @coerce) ? default : default.to_s)
|
|
35
|
+
|
|
36
|
+
return value unless @coerce
|
|
37
|
+
|
|
38
|
+
begin
|
|
39
|
+
@coerce.call(value)
|
|
40
|
+
rescue ArgumentError, TypeError => e
|
|
41
|
+
context.add_error("cannot coerce #{var_name}=#{value.inspect}: #{e.message}")
|
|
42
|
+
nil
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
data/lib/nero/error.rb
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
class Error
|
|
5
|
+
attr_reader :message
|
|
6
|
+
|
|
7
|
+
def initialize(message)
|
|
8
|
+
@message = message
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def to_s = message
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
class ParseError < StandardError
|
|
15
|
+
attr_reader :errors
|
|
16
|
+
|
|
17
|
+
def initialize(errors)
|
|
18
|
+
@errors = errors
|
|
19
|
+
super(errors.map(&:message).join(", "))
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
class FormatTag < BaseTag
|
|
5
|
+
def resolve(args, context:)
|
|
6
|
+
template, *fmt_args = args
|
|
7
|
+
if fmt_args.any? && fmt_args.all?(Hash)
|
|
8
|
+
fmt_args = [fmt_args.reduce({}, :merge).transform_keys(&:to_sym)]
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
format(template, *fmt_args)
|
|
12
|
+
rescue KeyError, ArgumentError => e
|
|
13
|
+
context.add_error("format error: #{e.message}")
|
|
14
|
+
nil
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
data/lib/nero/ip_tag.rb
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ipaddr"
|
|
4
|
+
|
|
5
|
+
module Nero
|
|
6
|
+
# An IPAddr from an address or a CIDR range.
|
|
7
|
+
#
|
|
8
|
+
# admin: !ip 10.0.0.1
|
|
9
|
+
# office: !ip 192.168.0.0/24
|
|
10
|
+
# admin_ip: !ip [!env [ADMIN_IP, 127.0.0.1]] # a sequence of one, to nest a tag
|
|
11
|
+
# proxies: # a list: one !ip per item
|
|
12
|
+
# - !ip 173.245.48.0/20
|
|
13
|
+
# - !ip 2400:cb00::/32
|
|
14
|
+
#
|
|
15
|
+
# IPAddr#include? tells whether an address is in a range:
|
|
16
|
+
# config["office"].include?(request.remote_ip)
|
|
17
|
+
class IpTag < BaseTag
|
|
18
|
+
def resolve(args, context:)
|
|
19
|
+
unless args.is_a?(Array) && args.size == 1 && args.first.is_a?(String)
|
|
20
|
+
context.add_error("!ip expects one address or CIDR range, got #{args.inspect} " \
|
|
21
|
+
"(for several, use a list with one !ip per item)")
|
|
22
|
+
return
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
IPAddr.new(args.first)
|
|
26
|
+
rescue IPAddr::Error
|
|
27
|
+
context.add_error("!ip #{args.first.inspect} is not a valid IP address or CIDR range")
|
|
28
|
+
nil
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
data/lib/nero/parser.rb
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
class Parser
|
|
5
|
+
TO_INT = ->(v) { Integer(v, 10) }
|
|
6
|
+
TO_FLOAT = ->(v) { Float(v) } # no base: Float() never reads "08" as octal
|
|
7
|
+
|
|
8
|
+
BOOL_YES = %w[1 y yes true on].freeze
|
|
9
|
+
BOOL_NO = %w[0 n no false off].freeze
|
|
10
|
+
TO_BOOL = ->(v) do
|
|
11
|
+
val = v.downcase.strip
|
|
12
|
+
return true if BOOL_YES.include?(val)
|
|
13
|
+
return false if BOOL_NO.include?(val)
|
|
14
|
+
|
|
15
|
+
raise ArgumentError, "Can't coerce #{v.inspect} to boolean. Acceptable values: #{(BOOL_YES + BOOL_NO).join("/")}"
|
|
16
|
+
end
|
|
17
|
+
TO_PATH = ->(v) { Pathname.new(v) }
|
|
18
|
+
TO_IP = ->(v) do
|
|
19
|
+
IPAddr.new(v)
|
|
20
|
+
rescue IPAddr::Error
|
|
21
|
+
raise ArgumentError, "not a valid IP address or CIDR range"
|
|
22
|
+
end
|
|
23
|
+
# "a, b,,c" → ["a", "b", "c"]; a fallback sequence ([a, b]) is used as is.
|
|
24
|
+
TO_LIST = ->(v) { v.is_a?(Array) ? v.map(&:to_s) : v.split(",").map(&:strip).reject(&:empty?) }
|
|
25
|
+
|
|
26
|
+
# Classes YAML may instantiate, as YAML.load allows by default.
|
|
27
|
+
PERMITTED_CLASSES = %w[Symbol].freeze
|
|
28
|
+
|
|
29
|
+
# symbolize_names: as in YAML.load, string keys become symbols (other keys stay as they are).
|
|
30
|
+
# all_optional: every value that can be missing (env vars, Rails credentials) is optional:
|
|
31
|
+
# missing resolves to the fallback or nil instead of an error. For tasks that load the
|
|
32
|
+
# config without needing it, e.g. `rails assets:precompile` or `rails credentials:edit`.
|
|
33
|
+
# Defaults to whether NERO_ALL_OPTIONAL is set (non-empty) in environ. The old name
|
|
34
|
+
# NERO_ENV_ALL_OPTIONAL still works, with a deprecation warning, until 0.8.
|
|
35
|
+
def initialize(environ: ENV, root: nil, permitted_classes: PERMITTED_CLASSES, symbolize_names: false,
|
|
36
|
+
all_optional: nil, &block)
|
|
37
|
+
@environ = environ
|
|
38
|
+
if all_optional.nil?
|
|
39
|
+
@deprecated_all_optional = set?("NERO_ENV_ALL_OPTIONAL") && !set?("NERO_ALL_OPTIONAL")
|
|
40
|
+
all_optional = set?("NERO_ALL_OPTIONAL") || set?("NERO_ENV_ALL_OPTIONAL")
|
|
41
|
+
end
|
|
42
|
+
@all_optional = all_optional
|
|
43
|
+
@root = root&.to_s
|
|
44
|
+
@permitted_classes = permitted_classes
|
|
45
|
+
@symbolize_names = symbolize_names
|
|
46
|
+
@tags = {}
|
|
47
|
+
add_tag("env", EnvTag.new)
|
|
48
|
+
add_tag("env?", EnvTag.new(optional: true))
|
|
49
|
+
add_tag("env/int", EnvTag.new(coerce: TO_INT))
|
|
50
|
+
add_tag("env/int?", EnvTag.new(coerce: TO_INT, optional: true,
|
|
51
|
+
deprecated: ["!env/int? is deprecated", use: "!env?/int", removed_in: "0.8"]))
|
|
52
|
+
add_tag("env?/int", EnvTag.new(coerce: TO_INT, optional: true))
|
|
53
|
+
add_tag("env/integer", EnvTag.new(coerce: TO_INT))
|
|
54
|
+
add_tag("env/integer?", EnvTag.new(coerce: TO_INT, optional: true,
|
|
55
|
+
deprecated: ["!env/integer? is deprecated", use: "!env?/integer", removed_in: "0.8"]))
|
|
56
|
+
add_tag("env?/integer", EnvTag.new(coerce: TO_INT, optional: true))
|
|
57
|
+
add_tag("env/bool", EnvTag.new(coerce: TO_BOOL))
|
|
58
|
+
add_tag("env/bool?", EnvTag.new(coerce: TO_BOOL, optional: true,
|
|
59
|
+
deprecated: ["!env/bool? is deprecated", use: "!env?/bool", removed_in: "0.8"]))
|
|
60
|
+
add_tag("env?/bool", EnvTag.new(coerce: TO_BOOL, optional: true))
|
|
61
|
+
add_tag("env/boolean", EnvTag.new(coerce: TO_BOOL))
|
|
62
|
+
add_tag("env/boolean?", EnvTag.new(coerce: TO_BOOL, optional: true,
|
|
63
|
+
deprecated: ["!env/boolean? is deprecated", use: "!env?/boolean", removed_in: "0.8"]))
|
|
64
|
+
add_tag("env?/boolean", EnvTag.new(coerce: TO_BOOL, optional: true))
|
|
65
|
+
add_tag("env/float", EnvTag.new(coerce: TO_FLOAT))
|
|
66
|
+
add_tag("env/float?", EnvTag.new(coerce: TO_FLOAT, optional: true,
|
|
67
|
+
deprecated: ["!env/float? is deprecated", use: "!env?/float", removed_in: "0.8"]))
|
|
68
|
+
add_tag("env?/float", EnvTag.new(coerce: TO_FLOAT, optional: true))
|
|
69
|
+
add_tag("env/path", EnvTag.new(coerce: TO_PATH))
|
|
70
|
+
add_tag("env/path?", EnvTag.new(coerce: TO_PATH, optional: true,
|
|
71
|
+
deprecated: ["!env/path? is deprecated", use: "!env?/path", removed_in: "0.8"]))
|
|
72
|
+
add_tag("env?/path", EnvTag.new(coerce: TO_PATH, optional: true))
|
|
73
|
+
add_tag("env/ip", EnvTag.new(coerce: TO_IP))
|
|
74
|
+
add_tag("env?/ip", EnvTag.new(coerce: TO_IP, optional: true))
|
|
75
|
+
add_tag("env/list", EnvTag.new(coerce: TO_LIST))
|
|
76
|
+
add_tag("env?/list", EnvTag.new(coerce: TO_LIST, optional: true))
|
|
77
|
+
add_tag("str/format", FormatTag.new)
|
|
78
|
+
add_tag("format", FormatTag.new)
|
|
79
|
+
add_tag("ref", RefTag.new)
|
|
80
|
+
add_tag("ip", IpTag.new)
|
|
81
|
+
add_tag("path/git_root", RootPathTag.new(containing: ".git"))
|
|
82
|
+
block&.call(self)
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def add_tag(name, handler)
|
|
86
|
+
@tags[name] = handler.is_a?(Proc) ? ProcTag.new(handler) : handler
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def parse(yaml, dir: nil)
|
|
90
|
+
tree = ::Psych.parse_stream(yaml)
|
|
91
|
+
ctx = Context.new(environ: @environ, dir:, all_optional: @all_optional)
|
|
92
|
+
if @deprecated_all_optional
|
|
93
|
+
ctx.deprecate("NERO_ENV_ALL_OPTIONAL is deprecated", use: "NERO_ALL_OPTIONAL", removed_in: "0.8")
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
if @root
|
|
97
|
+
mark_inactive_roots(tree)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
visitor = Visitor.build(@tags, ctx, permitted_classes: @permitted_classes, symbolize_names: @symbolize_names)
|
|
101
|
+
begin
|
|
102
|
+
result = visitor.accept(tree)
|
|
103
|
+
rescue ::Psych::DisallowedClass => e
|
|
104
|
+
ctx.add_error("#{e.message} (allow it with permitted_classes:)")
|
|
105
|
+
return Result.new(nil, errors: ctx.errors.dup.freeze, warnings: ctx.warnings.dup.freeze)
|
|
106
|
+
end
|
|
107
|
+
value = result.first
|
|
108
|
+
|
|
109
|
+
if @root
|
|
110
|
+
unless value.is_a?(Hash) && value.key?(key(@root))
|
|
111
|
+
ctx.add_error("root #{@root.inspect} not found in top-level keys")
|
|
112
|
+
return Result.new(nil, errors: ctx.errors.dup.freeze, warnings: ctx.warnings.dup.freeze)
|
|
113
|
+
end
|
|
114
|
+
value = value[key(@root)]
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
value = resolve_refs(value, value, ctx) if contains_ref?(value)
|
|
118
|
+
Result.new(value, errors: ctx.errors.dup.freeze, warnings: ctx.warnings.dup.freeze)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def parse_file(path)
|
|
122
|
+
dir = File.dirname(File.realpath(path))
|
|
123
|
+
parse(File.read(path), dir:)
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
private
|
|
127
|
+
|
|
128
|
+
def set?(var) = !@environ.fetch(var, "").empty?
|
|
129
|
+
|
|
130
|
+
# A key as it appears in the loaded result (the YAML nodes themselves always hold strings).
|
|
131
|
+
def key(name) = @symbolize_names ? name.to_sym : name
|
|
132
|
+
|
|
133
|
+
def mark_inactive_roots(tree)
|
|
134
|
+
doc = tree.children.first
|
|
135
|
+
mapping = doc&.root
|
|
136
|
+
return unless mapping.is_a?(::Psych::Nodes::Mapping)
|
|
137
|
+
|
|
138
|
+
root_node = mapping.children.each_slice(2).find { |k, _| k.value == @root }&.last
|
|
139
|
+
used_anchors = root_node ? collect_aliases(root_node) : Set.new
|
|
140
|
+
|
|
141
|
+
mapping.children.each_slice(2) do |key_node, val_node|
|
|
142
|
+
next if key_node.value == @root
|
|
143
|
+
next if used_anchors.include?(val_node.anchor)
|
|
144
|
+
|
|
145
|
+
strip_custom_tags(val_node)
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def collect_aliases(node, result = Set.new)
|
|
150
|
+
if node.is_a?(::Psych::Nodes::Alias)
|
|
151
|
+
result << node.anchor
|
|
152
|
+
elsif node.respond_to?(:children) && node.children
|
|
153
|
+
node.children.each { |child| collect_aliases(child, result) }
|
|
154
|
+
end
|
|
155
|
+
result
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def strip_custom_tags(node)
|
|
159
|
+
case node
|
|
160
|
+
when ::Psych::Nodes::Scalar, ::Psych::Nodes::Sequence, ::Psych::Nodes::Mapping
|
|
161
|
+
node.tag = nil if node.tag&.start_with?("!")
|
|
162
|
+
end
|
|
163
|
+
return unless node.respond_to?(:children) && node.children
|
|
164
|
+
node.children.each { |child| strip_custom_tags(child) }
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def contains_ref?(value)
|
|
168
|
+
case value
|
|
169
|
+
when Ref, Deferred then true
|
|
170
|
+
when Hash then value.values.any? { |v| contains_ref?(v) }
|
|
171
|
+
when Array then value.any? { |v| contains_ref?(v) }
|
|
172
|
+
else false
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def resolve_refs(value, root, ctx, visited = Set.new)
|
|
177
|
+
case value
|
|
178
|
+
when Ref
|
|
179
|
+
key = value.path.join(".")
|
|
180
|
+
if visited.include?(key)
|
|
181
|
+
ctx.add_error("circular reference: #{key}")
|
|
182
|
+
return nil
|
|
183
|
+
end
|
|
184
|
+
target = value.path.reduce(root) { |h, k| h.is_a?(Hash) ? h[key(k)] : nil }
|
|
185
|
+
if target.nil?
|
|
186
|
+
ctx.add_error("unknown ref #{key}")
|
|
187
|
+
return nil
|
|
188
|
+
end
|
|
189
|
+
resolve_refs(target, root, ctx, visited | [key])
|
|
190
|
+
when Deferred
|
|
191
|
+
resolved_args = resolve_refs(value.args, root, ctx, visited)
|
|
192
|
+
value.tag.resolve(resolved_args, context: ctx)
|
|
193
|
+
when Hash
|
|
194
|
+
value.transform_values { |v| resolve_refs(v, root, ctx, visited) }
|
|
195
|
+
when Array
|
|
196
|
+
value.map { |v| resolve_refs(v, root, ctx, visited) }
|
|
197
|
+
else
|
|
198
|
+
value
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nero
|
|
4
|
+
module Rails
|
|
5
|
+
class CredentialsTag < BaseTag
|
|
6
|
+
# credentials: anything responding to #dig. Defaults to Rails.application.credentials,
|
|
7
|
+
# looked up when the tag resolves, so a parser can be built before (or without) an app.
|
|
8
|
+
def initialize(credentials = nil)
|
|
9
|
+
@credentials = credentials
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def credentials
|
|
13
|
+
@credentials || ::Rails.application.credentials
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def resolve(args, context:)
|
|
17
|
+
keys = args.map(&:to_sym)
|
|
18
|
+
value = credentials.dig(*keys)
|
|
19
|
+
return value unless value.nil?
|
|
20
|
+
return nil if context.all_optional?
|
|
21
|
+
|
|
22
|
+
context.add_error("credential #{args.join(".")} not found")
|
|
23
|
+
nil
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|