nero 0.7.0.rc2 → 0.7.0.rc4

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.
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
@@ -0,0 +1,4 @@
1
+ # For (personal) irb-settings that take precendence over .irbrc (excluded from git).
2
+ puts "Loading #{__FILE__}"
3
+ # IRB.conf[:HISTORY_FILE] = "tmp/.irb_history"
4
+ # IRB.conf[:HISTORY] = -1 # all of it
data/lib/nero/context.rb CHANGED
@@ -2,16 +2,30 @@
2
2
 
3
3
  module Nero
4
4
  class Context
5
- attr_reader :errors, :environ, :dir
5
+ attr_reader :environ, :dir, :errors, :warnings
6
6
 
7
- def initialize(environ:, errors:, dir: nil)
7
+ def initialize(environ:, dir: nil, all_optional: false)
8
8
  @environ = environ
9
- @errors = errors
10
9
  @dir = dir || File.realpath(".")
10
+ @all_optional = all_optional
11
+ @errors = []
12
+ @warnings = Set.new
11
13
  end
12
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
+
13
19
  def add_error(message)
14
20
  @errors << Error.new(message)
15
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
16
30
  end
17
31
  end
data/lib/nero/env_tag.rb CHANGED
@@ -2,28 +2,42 @@
2
2
 
3
3
  module Nero
4
4
  class EnvTag < BaseTag
5
- def initialize(coerce: nil, optional: false)
5
+ def initialize(coerce: nil, optional: false, deprecated: nil)
6
+ @deprecated = deprecated
6
7
  @coerce = coerce
7
8
  @optional = optional
8
9
  end
9
10
 
11
+ def deprecated? = !!@deprecated
12
+
10
13
  def resolve(args, context:)
14
+ if (msg, opts = @deprecated)
15
+ context.deprecate(msg, **opts)
16
+ end
11
17
  var_name = args[0]
12
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
+
13
25
  raw = context.environ[var_name]
14
26
 
15
27
  if raw.nil? && default.nil?
16
- context.add_error("environment variable #{var_name} is not set") unless @optional
17
- return nil
28
+ context.add_error("environment variable #{var_name} is not set") unless @optional || context.all_optional?
29
+ return
18
30
  end
19
31
 
20
- value = raw || default.to_s
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)
21
35
 
22
36
  return value unless @coerce
23
37
 
24
38
  begin
25
39
  @coerce.call(value)
26
- rescue ArgumentError => e
40
+ rescue ArgumentError, TypeError => e
27
41
  context.add_error("cannot coerce #{var_name}=#{value.inspect}: #{e.message}")
28
42
  nil
29
43
  end
@@ -3,12 +3,13 @@
3
3
  module Nero
4
4
  class FormatTag < BaseTag
5
5
  def resolve(args, context:)
6
- template = args[0]
7
- opts = args.each_with_object({}) do |arg, h|
8
- h.merge!(arg.transform_keys(&:to_sym)) if arg.is_a?(Hash)
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
9
  end
10
- format(template, opts)
11
- rescue KeyError => e
10
+
11
+ format(template, *fmt_args)
12
+ rescue KeyError, ArgumentError => e
12
13
  context.add_error("format error: #{e.message}")
13
14
  nil
14
15
  end
@@ -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 CHANGED
@@ -2,32 +2,83 @@
2
2
 
3
3
  module Nero
4
4
  class Parser
5
- TO_INT = ->(v) { Integer(v) }
6
- TO_FLOAT = ->(v) { Float(v) }
7
- TO_BOOL = ->(v) { !%w[0 false no off].include?(v.downcase) }
8
- TO_PATH = ->(v) { Pathname.new(v) }
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)
9
14
 
10
- def initialize(environ: ENV, root: nil, &block)
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)
11
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
12
43
  @root = root&.to_s
44
+ @permitted_classes = permitted_classes
45
+ @symbolize_names = symbolize_names
13
46
  @tags = {}
14
47
  add_tag("env", EnvTag.new)
15
48
  add_tag("env?", EnvTag.new(optional: true))
16
49
  add_tag("env/int", EnvTag.new(coerce: TO_INT))
17
- add_tag("env/int?", EnvTag.new(coerce: TO_INT, optional: true))
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))
18
53
  add_tag("env/integer", EnvTag.new(coerce: TO_INT))
19
- add_tag("env/integer?", EnvTag.new(coerce: TO_INT, optional: true))
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))
20
57
  add_tag("env/bool", EnvTag.new(coerce: TO_BOOL))
21
- add_tag("env/bool?", EnvTag.new(coerce: TO_BOOL, optional: true))
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))
22
61
  add_tag("env/boolean", EnvTag.new(coerce: TO_BOOL))
23
- add_tag("env/boolean?", EnvTag.new(coerce: TO_BOOL, optional: true))
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))
24
65
  add_tag("env/float", EnvTag.new(coerce: TO_FLOAT))
25
- add_tag("env/float?", EnvTag.new(coerce: TO_FLOAT, optional: true))
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))
26
69
  add_tag("env/path", EnvTag.new(coerce: TO_PATH))
27
- add_tag("env/path?", EnvTag.new(coerce: TO_PATH, optional: true))
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))
28
77
  add_tag("str/format", FormatTag.new)
29
78
  add_tag("format", FormatTag.new)
30
79
  add_tag("ref", RefTag.new)
80
+ add_tag("ip", IpTag.new)
81
+ add_tag("path/git_root", RootPathTag.new(containing: ".git"))
31
82
  block&.call(self)
32
83
  end
33
84
 
@@ -36,37 +87,49 @@ module Nero
36
87
  end
37
88
 
38
89
  def parse(yaml, dir: nil)
39
- errors = []
40
90
  tree = ::Psych.parse_stream(yaml)
41
- ctx = Context.new(environ: @environ, errors: errors, dir: dir)
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
42
95
 
43
96
  if @root
44
97
  mark_inactive_roots(tree)
45
98
  end
46
99
 
47
- visitor = Visitor.build(@tags, ctx)
48
- result = visitor.accept(tree)
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
49
107
  value = result.first
50
108
 
51
109
  if @root
52
- unless value.is_a?(Hash) && value.key?(@root)
110
+ unless value.is_a?(Hash) && value.key?(key(@root))
53
111
  ctx.add_error("root #{@root.inspect} not found in top-level keys")
54
- return Result.new(nil, errors.freeze)
112
+ return Result.new(nil, errors: ctx.errors.dup.freeze, warnings: ctx.warnings.dup.freeze)
55
113
  end
56
- value = value[@root]
114
+ value = value[key(@root)]
57
115
  end
58
116
 
59
117
  value = resolve_refs(value, value, ctx) if contains_ref?(value)
60
- Result.new(value, errors.freeze)
118
+ Result.new(value, errors: ctx.errors.dup.freeze, warnings: ctx.warnings.dup.freeze)
61
119
  end
62
120
 
63
121
  def parse_file(path)
64
122
  dir = File.dirname(File.realpath(path))
65
- parse(File.read(path), dir: dir)
123
+ parse(File.read(path), dir:)
66
124
  end
67
125
 
68
126
  private
69
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
+
70
133
  def mark_inactive_roots(tree)
71
134
  doc = tree.children.first
72
135
  mapping = doc&.root
@@ -118,7 +181,7 @@ module Nero
118
181
  ctx.add_error("circular reference: #{key}")
119
182
  return nil
120
183
  end
121
- target = value.path.reduce(root) { |h, k| h.is_a?(Hash) ? h[k] : nil }
184
+ target = value.path.reduce(root) { |h, k| h.is_a?(Hash) ? h[key(k)] : nil }
122
185
  if target.nil?
123
186
  ctx.add_error("unknown ref #{key}")
124
187
  return nil
@@ -3,18 +3,21 @@
3
3
  module Nero
4
4
  module Rails
5
5
  class CredentialsTag < BaseTag
6
- attr_reader :credentials
7
-
8
- # TODO lookup?
9
- def initialize(credentials)
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)
10
9
  @credentials = credentials
11
10
  end
12
11
 
12
+ def credentials
13
+ @credentials || ::Rails.application.credentials
14
+ end
15
+
13
16
  def resolve(args, context:)
14
17
  keys = args.map(&:to_sym)
15
- #value = ::Rails.application.credentials.dig(*keys)
16
18
  value = credentials.dig(*keys)
17
- return value if value
19
+ return value unless value.nil?
20
+ return nil if context.all_optional?
18
21
 
19
22
  context.add_error("credential #{args.join(".")} not found")
20
23
  nil
data/lib/nero/rails.rb CHANGED
@@ -7,11 +7,11 @@ require_relative "rails/string_inquirer_tag"
7
7
  module Nero
8
8
  module Rails
9
9
  module ParserExtension
10
- def initialize(environ: ENV, root: nil, &block)
11
- super(environ:, root:)
12
- add_tag("credentials", Nero::Rails::CredentialsTag.new(::Rails.application.credentials))
10
+ def initialize(environ: ENV, root: nil, **opts, &block)
11
+ # &nil: the user's block runs once, below, after the Rails tags, so it can override them.
12
+ super(environ:, root:, **opts, &nil)
13
+ add_tag("credentials", Nero::Rails::CredentialsTag.new)
13
14
  add_tag("path/rails_root", RootPathTag.new(containing: "config.ru"))
14
- add_tag("secret_key_base", ->(_, **) { ::Rails.application.secret_key_base })
15
15
  add_tag("str/inquirer", Nero::Rails::StringInquirerTag.new)
16
16
  add_tag("duration", Nero::Rails::DurationTag.new)
17
17
  block&.call(self)
@@ -26,7 +26,13 @@ module Nero
26
26
  module Rails
27
27
  module DefaultEnv
28
28
  def config_for(file, env: ::Rails.env, **opts, &block)
29
- super(file, env:, **opts, &block)
29
+ super
30
+ end
31
+
32
+ # Rails.root/config, so config_for works from any directory (specs, rake tasks).
33
+ # Falls back to ./config before the app has a root.
34
+ def config_dir
35
+ ::Rails.root ? Pathname(::Rails.root) / "config" : super
30
36
  end
31
37
  end
32
38
  end
data/lib/nero/ref.rb CHANGED
@@ -4,6 +4,7 @@ module Nero
4
4
  class Ref
5
5
  attr_reader :path
6
6
 
7
- def initialize(path) = @path = path.split(".")
7
+ # path: the keys to follow, e.g. ["a", "c"] for `!ref a.c`.
8
+ def initialize(path) = @path = path
8
9
  end
9
10
  end
data/lib/nero/ref_tag.rb CHANGED
@@ -1,9 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nero
4
+ # `!ref a.c` (preferred) or the sequence form `!ref [a, c]` (as in Nero < 0.7).
5
+ # Segments are split on ".", so `!ref [a.b, c]` is `a.b.c`.
4
6
  class RefTag < BaseTag
5
7
  def resolve(args, context:)
6
- Ref.new(args[0].to_s)
8
+ ref_path = args.flat_map { _1.to_s.split(".") }
9
+ context.deprecate "!ref [#{args.join(", ")}] is deprecated", use: "!ref #{ref_path.join(".")}", removed_in: "0.8" if args.size > 1
10
+
11
+ Ref.new(ref_path)
7
12
  end
8
13
  end
9
14
  end
data/lib/nero/result.rb CHANGED
@@ -2,14 +2,16 @@
2
2
 
3
3
  module Nero
4
4
  class Result
5
- attr_reader :value, :errors
5
+ attr_reader :value, :errors, :warnings
6
6
 
7
- def initialize(value, errors = [])
7
+ def initialize(value, errors: [], warnings: [])
8
8
  @value = value
9
9
  @errors = errors
10
+ @warnings = warnings
10
11
  end
11
12
 
12
13
  def ok? = errors.empty?
14
+ def warnings? = warnings.any?
13
15
 
14
16
  def value!
15
17
  raise ParseError, errors unless ok?