envpact 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ea8d94a55e0713c1d0d76ce40d98d6e968f8c7bdb9192c93321108fe30baf6bf
4
+ data.tar.gz: 342ec3385b66b5e9cfbce86d0fb5b063545c5ccb46ca3850288664a2e994e515
5
+ SHA512:
6
+ metadata.gz: ef274e41ef38671428929c754517a70fe64d8a5ce537ede93a88afb9647ff29e8ffcfa7402612e715f5b626458c037b29e113458865cc857d0781d8b59b1f722
7
+ data.tar.gz: '008ba026353f7bed742bb0c1dd509134bdb83f6e49d1091f13b75f7eba4fa70f31a9395c1ab6edb225ac0ae5948d43a0c312aa27c4a5eda6a5fa31f16f9af1cb'
data/CHANGELOG.md ADDED
@@ -0,0 +1,56 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-10-25
4
+
5
+ envpact is the successor of [envspec](https://rubygems.org/gems/envspec) 0.1.2:
6
+ same idea, renamed and redesigned around three checkpoints (local, pre-deploy,
7
+ boot). Breaking changes throughout; envspec had no real users.
8
+
9
+ - **Renamed** gem/module/executable: `envspec`/`EnvSpec` → `envpact`/`EnvPact`.
10
+ - **New `check` API:** `spec.check(values, env:, strict:, extras:)` returns a
11
+ `Result` (`ok?`, `errors`, `warnings`, `applied_sections`) of `Problem`s;
12
+ `check!` raises `ValidationError#result`. Replaces `validate`/`validate!`.
13
+ `env:` is always required.
14
+ - **Secret masking:** problem messages never include a secret value
15
+ (`Problem#value` is nil for secrets); `check --show-values` reveals them.
16
+ - **Empty values count as absent** everywhere.
17
+ - **Unknown keys** are warnings (errors with `--strict`) and are never reported
18
+ when checking process ENV.
19
+ - **Syntax:** `url` type (validated) replaces `dsn`; new `[shared]` header;
20
+ `#` starts a comment only at line start or after whitespace; quoted defaults
21
+ (`"..."`, escapes `\"` `\\`); CRLF and UTF-8 BOM accepted; a key declared
22
+ as both ConfigMap and Secret, or a default that doesn't match its type, is a
23
+ parse error. Files are read as UTF-8 regardless of locale.
24
+ - **CLI:** `check` reads `.env`, `.env.<env>`, `.env.local` (not for test),
25
+ `.env.<env>.local`, or `--from-env`; new `exec` boot wrapper (fills defaults,
26
+ then execs; env from `--env` or `$ENVPACT_ENV`); new `scan-prompt` for AI
27
+ agents; `--spec`/`$ENVPACT_SPEC` on every command; commands return exit codes
28
+ (0/1/2, 127 for `exec` command not found) instead of calling `exit`.
29
+ - **Removed:** `init` and the regex scanner/name heuristics (replaced by
30
+ `scan-prompt`).
31
+
32
+ ## envspec history
33
+
34
+ ### 0.1.2 — 2026-05-04
35
+
36
+ - Split CLI into one file per subcommand under `lib/envspec/cli/`:
37
+ `command.rb` (base class), `lint.rb`, `check.rb`, `init.rb`. Adding a new
38
+ subcommand is now: write a class inheriting from `EnvSpec::CLI::Command`,
39
+ register it in `EnvSpec::CLI::COMMANDS`.
40
+ - Aligned formatting in global help.
41
+
42
+ ### 0.1.1 — 2026-05-04
43
+
44
+ - Refactor CLI into `EnvSpec::CLI` with proper subcommand structure (per-subcommand `OptionParser` with banners, options, and `-h` help). Still pure stdlib.
45
+ - `envspec help <command>` and `envspec <command> -h` now show subcommand-specific usage.
46
+ - Better exit codes (2 for usage errors, 1 for parse/validation errors, 0 for success).
47
+
48
+ ### 0.1.0 — 2026-05-04
49
+
50
+ Initial release.
51
+
52
+ - Parser for `env.spec` syntax v5 (`[secrets]` modifier, `[env: …]` selector, scoped configmap/secrets, types `str | int | bool | dsn | enum`).
53
+ - Validator: presence + type-level checks (int/bool/enum/dsn).
54
+ - CLI: `envspec lint`, `envspec check`, `envspec init`.
55
+ - `init` scans Ruby/Python/JS/Go/Shell sources and generates a starter `env.spec` with heuristic-based suggestions.
56
+ - Zero runtime dependencies; Ruby ≥ 2.5.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leadfy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # envpact
2
+
3
+ An env var contract for apps. One file, `env.spec`, declares which env vars an
4
+ app needs — names, types, required/optional, defaults, Secret vs ConfigMap, and
5
+ per-env differences. It never holds values. The same contract is checked at
6
+ three moments:
7
+
8
+ 1. **Locally** — `envpact check --env=development` against your `.env*` files.
9
+ 2. **Before deploy** — a deploy tool (e.g. kdep) assembles the values that will be
10
+ in the cluster and calls the Ruby API; a failure blocks the deploy.
11
+ 3. **At boot** — `envpact exec --env=production -- <cmd>` checks the real process
12
+ ENV and refuses to start the app if the contract isn't met.
13
+
14
+ Pure Ruby, **zero runtime dependencies**, Ruby ≥ 2.5. envpact knows nothing about
15
+ kdep, Infisical or Kubernetes: its interface is *contract + env name + values →
16
+ ok or a list of problems*. It never writes to disk and never prints a secret
17
+ value (unless you pass `--show-values`).
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ gem install envpact
23
+ ```
24
+
25
+ ## Commands
26
+
27
+ ```sh
28
+ envpact lint # syntax check ./env.spec
29
+ envpact check --env=test # check .env, .env.test, .env.test.local
30
+ envpact check --env=x --from-env # check the current process ENV instead
31
+ envpact exec --env=production -- bin/rails server # boot check, then exec
32
+ envpact scan-prompt | claude # have an agent write env.spec for this repo
33
+ ```
34
+
35
+ - The contract path defaults to `./env.spec`; override with `--spec=PATH` or
36
+ `$ENVPACT_SPEC`.
37
+ - `--env` is always required (`exec` also reads `$ENVPACT_ENV`). Any env name
38
+ is valid: an env without an `[env: …]` section gets only the shared keys, and
39
+ every check says which sections it applied:
40
+ `✓ env.spec satisfied (env: prod — shared only; sections in spec: production)`.
41
+ - `check` reads, in order (later overrides earlier): `.env`, `.env.<env>`,
42
+ `.env.local` (skipped for `test`), `.env.<env>.local`. No interpolation, no
43
+ multiline values.
44
+ - Keys present but not in the contract are warnings; `--strict` makes them
45
+ errors. They are never reported when checking process ENV.
46
+ - `exec` fills defaults for absent or empty keys, then replaces itself with the
47
+ command. Exit codes: 0 ok, 1 contract not satisfied, 2 usage error, 127 command
48
+ not found.
49
+
50
+ Composes with Infisical (or anything that injects env) without coupling:
51
+
52
+ ```sh
53
+ infisical run --env=dev -- envpact exec --env=development -- bin/rails s
54
+ ```
55
+
56
+ ## env.spec syntax
57
+
58
+ ```
59
+ # shared (all envs) -- the top of the file is the default for every env
60
+ APP_NAME
61
+ LOG_LEVEL: enum(debug, info, warn, error) = info
62
+ DEBUG?: bool
63
+ PORT: int = 3000
64
+ PUBLIC_URL: url
65
+
66
+ [secrets]
67
+ DB_PASS
68
+ OPENAI_API_KEY
69
+
70
+ [env: production]
71
+ SENTRY_DSN: url
72
+ [secrets]
73
+ STRIPE_LIVE_KEY
74
+
75
+ [env: production, staging]
76
+ CDN_HOST
77
+
78
+ [shared]
79
+ FEATURE_FLAGS?
80
+ ```
81
+
82
+ - `KEY` — required string, ConfigMap, in the current scope.
83
+ - `KEY?` — optional.
84
+ - `KEY: type` — `str` (default) | `int` | `bool` | `url` | `enum(a, b, c)`.
85
+ - `bool` accepts `true false 1 0 yes no` (any case).
86
+ - `url` needs a scheme and a host: `postgres://u:p@h:5432/db`, `https://x.y`.
87
+ - `KEY = default` — default value, ConfigMap only; secrets cannot have defaults.
88
+ The default must be valid for the type (`PORT: int = 3OOO` is a lint error).
89
+ Quote it to keep `#` or surrounding spaces: `GREETING = "hi # there "`
90
+ (only `\"` and `\\` are escapes; any other backslash is kept).
91
+ - `[secrets]` — modifier: following keys are Secrets; scope unchanged.
92
+ - `[env: name]` / `[env: a, b]` — selector: following keys apply only to those
93
+ envs; type resets to ConfigMap. Env names are free-form (`[A-Za-z0-9_-]+`).
94
+ - `[shared]` — selector: back to the shared scope (all envs); type resets to
95
+ ConfigMap.
96
+ - `#` starts a comment at the start of a line or after whitespace
97
+ (`URL = http://x/a#frag` keeps the `#frag`).
98
+ - An env with no `[env: …]` section gets only the shared keys. A key may not be
99
+ declared in overlapping scopes, may not be both ConfigMap and Secret, and must
100
+ have the same type in every env.
101
+ - Empty values count as absent.
102
+
103
+ ## Library API
104
+
105
+ ```ruby
106
+ require "envpact"
107
+
108
+ spec = EnvPact.parse_file("env.spec") # or EnvPact.parse(text)
109
+ spec.envs # env names that have sections
110
+ spec.configmap_for("production") # shared + production, {key => Entry}
111
+ spec.secrets_for("production")
112
+
113
+ result = spec.check(values, env: "production", strict: false)
114
+ result.ok? # no errors (warnings allowed)
115
+ result.errors # [EnvPact::Problem] :missing / :invalid (+ :extra if strict)
116
+ result.warnings # [EnvPact::Problem] :extra
117
+ result.applied_sections # ["shared", "production"]
118
+ result.errors.first.message # secret values are already masked
119
+
120
+ spec.check!(values, env: "production") # raises EnvPact::ValidationError (#result)
121
+ EnvPact::Dotenv.load(Dir.pwd, env: "test") # => { files: [...], values: {...} }
122
+ ```
123
+
124
+ `Problem#value` is `nil` for secrets. To reveal one deliberately (as
125
+ `check --show-values` does): `EnvPact::Message.format(problem, value: values[problem.key])`.
126
+
127
+ ## License
128
+
129
+ MIT.
data/exe/envpact ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ require "envpact"
3
+ exit EnvPact::CLI.run(ARGV)
@@ -0,0 +1,53 @@
1
+ class EnvPact
2
+ KEY_RE = /\A[A-Z][A-Z0-9_]*\z/.freeze
3
+
4
+ # Checks a values hash against the spec for one env.
5
+ #
6
+ # - required keys must be present and non-empty (empty counts as absent)
7
+ # - present values must parse as their declared type
8
+ # - keys not in the spec are warnings, or errors with strict: true;
9
+ # extras: false skips them entirely (process ENV is full of PATH etc.)
10
+ def check(values, env:, strict: false, extras: true)
11
+ configmap = configmap_for(env)
12
+ secrets = secrets_for(env)
13
+ errors = []
14
+ warnings = []
15
+
16
+ { false => configmap, true => secrets }.each do |secret, entries|
17
+ entries.each do |key, entry|
18
+ raw = values[key]
19
+ if raw.nil? || raw.empty?
20
+ next if entry.optional || !entry.default.nil?
21
+ errors << Problem.new(kind: :missing, key: key, secret: secret, line: entry.line)
22
+ elsif !Types.valid?(raw, entry.type, entry.enum_values)
23
+ errors << Problem.new(kind: :invalid, key: key, secret: secret, line: entry.line,
24
+ value: (secret ? nil : raw), type: entry.type, enum_values: entry.enum_values)
25
+ end
26
+ end
27
+ end
28
+
29
+ if extras
30
+ known = configmap.merge(secrets)
31
+ values.each_key do |key|
32
+ next unless KEY_RE.match?(key) && !known.key?(key)
33
+ (strict ? errors : warnings) << Problem.new(kind: :extra, key: key, secret: false)
34
+ end
35
+ end
36
+
37
+ Result.new(env: env, errors: errors, warnings: warnings, applied_sections: applied_sections(env))
38
+ end
39
+
40
+ def check!(values, env:, strict: false, extras: true)
41
+ result = check(values, env: env, strict: strict, extras: extras)
42
+ raise ValidationError.new(result) unless result.ok?
43
+ result
44
+ end
45
+
46
+ private
47
+
48
+ def applied_sections(env)
49
+ sections = ["shared"]
50
+ sections << env if @configmap.key?(env) || @secrets.key?(env)
51
+ sections
52
+ end
53
+ end
@@ -0,0 +1,45 @@
1
+ require_relative "command"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ class Check < Command
6
+ command_name "check"
7
+ summary "Check .env files (or process ENV) against an env.spec"
8
+ banner "Usage: envpact check --env=NAME [options]"
9
+ description <<~DESC
10
+ Validates values against an env.spec for one env. By default reads the
11
+ dotenv files for that env from the current directory
12
+ (.env, .env.<env>, .env.local, .env.<env>.local; .env.local is skipped
13
+ for test). Secret values are never printed unless --show-values.
14
+ DESC
15
+
16
+ def default_opts
17
+ { strict: false, show_values: false, from_env: false }
18
+ end
19
+
20
+ def configure(o, opts)
21
+ o.on("--env=NAME", "Env to check (required)") { |v| opts[:env] = v }
22
+ spec_option(o, opts)
23
+ o.on("--from-env", "Check the current process ENV, not files") { opts[:from_env] = true }
24
+ o.on("--strict", "Treat unknown env vars as errors") { opts[:strict] = true }
25
+ o.on("--show-values", "Show secret values in problem messages") { opts[:show_values] = true }
26
+ end
27
+
28
+ def call(_rest, opts)
29
+ env = opts[:env] or raise UsageError, "--env=NAME is required"
30
+ spec = load_spec(opts)
31
+
32
+ if opts[:from_env]
33
+ values = ENV.to_h
34
+ else
35
+ loaded = Dotenv.load(Dir.pwd, env: env)
36
+ values = loaded[:values]
37
+ puts "Read: #{loaded[:files].empty? ? '(no .env files found)' : loaded[:files].join(', ')}"
38
+ end
39
+
40
+ result = spec.check(values, env: env, strict: opts[:strict], extras: !opts[:from_env])
41
+ report(spec, result, opts, reveal: opts[:show_values] ? values : nil)
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,138 @@
1
+ require "optparse"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ # Raised for bad invocations; the dispatcher maps it to exit code 2.
6
+ class UsageError < EnvPact::Error; end
7
+
8
+ # Base class for a single CLI subcommand.
9
+ #
10
+ # Subclasses declare:
11
+ # - command_name (string, e.g. "lint")
12
+ # - summary (one-line description for global help)
13
+ # - configure(parser, opts) — define options on the OptionParser
14
+ # - call(argv, opts) — execute; return exit code
15
+ class Command
16
+ DEFAULT_SPEC = "env.spec".freeze
17
+
18
+ class << self
19
+ def command_name(value = nil)
20
+ @command_name = value if value
21
+ @command_name
22
+ end
23
+
24
+ def summary(value = nil)
25
+ @summary = value if value
26
+ @summary
27
+ end
28
+
29
+ def banner(value = nil)
30
+ @banner = value if value
31
+ @banner
32
+ end
33
+
34
+ def description(value = nil)
35
+ @description = value if value
36
+ @description
37
+ end
38
+ end
39
+
40
+ def initialize
41
+ @opts = default_opts
42
+ @help_requested = false
43
+ end
44
+
45
+ def default_opts
46
+ {}
47
+ end
48
+
49
+ def parser
50
+ @parser ||= build_parser
51
+ end
52
+
53
+ def build_parser
54
+ OptionParser.new do |o|
55
+ o.banner = self.class.banner || "Usage: envpact #{self.class.command_name}"
56
+ if self.class.description
57
+ o.separator ""
58
+ self.class.description.each_line { |ln| o.separator ln.chomp }
59
+ end
60
+ o.separator ""
61
+ o.separator "Options:"
62
+ configure(o, @opts)
63
+ o.on("-h", "--help", "Show help for this command") { @help_requested = true }
64
+ end
65
+ end
66
+
67
+ def configure(_parser, _opts)
68
+ # subclass override
69
+ end
70
+
71
+ def help
72
+ parser.help
73
+ end
74
+
75
+ # Subclasses override `call(argv, opts)`. The dispatcher invokes `run(argv)`.
76
+ def run(argv)
77
+ rest = parser.parse(argv)
78
+ if @help_requested
79
+ puts parser.help
80
+ return 0
81
+ end
82
+ call(rest, @opts)
83
+ end
84
+
85
+ def call(_rest, _opts)
86
+ raise NotImplementedError
87
+ end
88
+
89
+ protected
90
+
91
+ def die(msg, code = 1)
92
+ warn "envpact: #{msg}"
93
+ code
94
+ end
95
+
96
+ def spec_option(o, opts)
97
+ o.on("--spec=PATH", "Contract file (default: $ENVPACT_SPEC or ./#{DEFAULT_SPEC})") { |v| opts[:spec] = v }
98
+ end
99
+
100
+ def spec_path(opts)
101
+ opts[:spec] || ENV["ENVPACT_SPEC"] || DEFAULT_SPEC
102
+ end
103
+
104
+ def load_spec(opts)
105
+ path = spec_path(opts)
106
+ raise EnvPact::Error, "spec not found: #{path}" unless File.file?(path)
107
+ EnvPact.parse_file(path)
108
+ end
109
+
110
+ # Prints the result and returns the exit code. reveal: is the values
111
+ # hash when the user asked for --show-values; extras never show values.
112
+ def report(spec, result, opts, reveal: nil)
113
+ name = File.basename(spec_path(opts))
114
+ scope = "(#{scope_label(spec, result)})"
115
+ if result.ok?
116
+ puts "✓ #{name} satisfied #{scope}"
117
+ else
118
+ warn "✗ #{name} not satisfied #{scope}"
119
+ result.errors.each { |p| warn " - #{problem_text(p, reveal)}" }
120
+ end
121
+ result.warnings.each { |p| warn " ! #{problem_text(p, reveal)}" }
122
+ result.ok? ? 0 : 1
123
+ end
124
+
125
+ def scope_label(spec, result)
126
+ env = result.env
127
+ return "env: #{env} — shared + [env: #{env}]" if result.applied_sections.include?(env)
128
+ others = spec.envs
129
+ others.empty? ? "env: #{env} — shared only" : "env: #{env} — shared only; sections in spec: #{others.join(', ')}"
130
+ end
131
+
132
+ def problem_text(problem, reveal)
133
+ return problem.message if reveal.nil? || problem.kind == :extra
134
+ Message.format(problem, value: reveal[problem.key])
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,60 @@
1
+ require_relative "command"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ class Exec < Command
6
+ command_name "exec"
7
+ summary "Check process ENV, then replace this process with CMD"
8
+ banner "Usage: envpact exec [--env=NAME] [--spec=PATH] -- CMD [ARGS...]"
9
+ description <<~DESC
10
+ Boot check for containers and local runs. Validates the current process
11
+ ENV against the spec; on success fills in defaults for absent or empty
12
+ keys and execs CMD (envpact disappears from the process tree). On
13
+ failure prints the problems and exits 1 without starting CMD.
14
+ The env name comes from --env or $ENVPACT_ENV.
15
+ DESC
16
+
17
+ def configure(o, opts)
18
+ o.on("--env=NAME", "Env to check (default: $ENVPACT_ENV)") { |v| opts[:env] = v }
19
+ spec_option(o, opts)
20
+ end
21
+
22
+ # Everything after the first "--" is the command, untouched by
23
+ # OptionParser.
24
+ def run(argv)
25
+ sep = argv.index("--")
26
+ own, @command = sep ? [argv[0...sep], argv[(sep + 1)..-1]] : [argv, []]
27
+ super(own)
28
+ end
29
+
30
+ def call(_rest, opts)
31
+ env = opts[:env] || ENV["ENVPACT_ENV"]
32
+ raise UsageError, "--env=NAME (or $ENVPACT_ENV) is required" if env.nil? || env.empty?
33
+ raise UsageError, "missing command: envpact exec [options] -- CMD [ARGS...]" if @command.empty?
34
+
35
+ spec = load_spec(opts)
36
+ result = spec.check(ENV.to_h, env: env, extras: false)
37
+ return report(spec, result, opts) unless result.ok?
38
+
39
+ # stderr, so the app's stdout stays its own; shows which sections
40
+ # applied, which is how an ENVPACT_ENV typo becomes visible at boot.
41
+ warn "✓ #{File.basename(spec_path(opts))} satisfied (#{scope_label(spec, result)})"
42
+ fill_defaults(spec, env)
43
+ Kernel.exec(*@command)
44
+ rescue Errno::ENOENT
45
+ die("command not found: #{@command.first}", 127)
46
+ rescue Errno::EACCES, Errno::ENOEXEC => e
47
+ die("cannot execute: #{@command.first} (#{e.message})", 126)
48
+ end
49
+
50
+ private
51
+
52
+ def fill_defaults(spec, env)
53
+ spec.configmap_for(env).each do |key, entry|
54
+ next if entry.default.nil?
55
+ ENV[key] = entry.default if ENV[key].nil? || ENV[key].empty?
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,22 @@
1
+ require_relative "command"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ class Lint < Command
6
+ command_name "lint"
7
+ summary "Parse and validate syntax of an env.spec file"
8
+ banner "Usage: envpact lint [--spec=PATH]"
9
+ description "Parses an env.spec file and reports any syntax errors."
10
+
11
+ def configure(o, opts)
12
+ spec_option(o, opts)
13
+ end
14
+
15
+ def call(_rest, opts)
16
+ load_spec(opts)
17
+ puts "✓ #{spec_path(opts)} is valid"
18
+ 0
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ require_relative "command"
2
+
3
+ class EnvPact
4
+ class CLI
5
+ class ScanPromptCommand < Command
6
+ command_name "scan-prompt"
7
+ summary "Print instructions for an AI agent to write env.spec"
8
+ banner "Usage: envpact scan-prompt"
9
+ description <<~DESC
10
+ Prints a self-contained prompt that tells an agent (e.g. Claude) how to
11
+ find every env var in this repo and write or update env.spec.
12
+ Typical use: envpact scan-prompt | claude
13
+ DESC
14
+
15
+ def call(_rest, _opts)
16
+ print EnvPact::ScanPrompt.render
17
+ 0
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,82 @@
1
+ require_relative "cli/command"
2
+ require_relative "cli/lint"
3
+ require_relative "cli/check"
4
+ require_relative "cli/exec"
5
+ require_relative "cli/scan_prompt"
6
+
7
+ class EnvPact
8
+ # Dispatcher for `envpact` subcommands.
9
+ #
10
+ # Each subcommand is a class under EnvPact::CLI inheriting from
11
+ # EnvPact::CLI::Command. Register new commands by adding them to COMMANDS
12
+ # below and creating a file under lib/envpact/cli/.
13
+ class CLI
14
+ COMMANDS = {
15
+ "lint" => Lint,
16
+ "check" => Check,
17
+ "exec" => Exec,
18
+ "scan-prompt" => ScanPromptCommand,
19
+ }.freeze
20
+
21
+ def self.run(argv)
22
+ new.run(argv)
23
+ end
24
+
25
+ def run(argv)
26
+ argv = argv.dup
27
+ cmd = argv.shift
28
+
29
+ case cmd
30
+ when nil, "help", "-h", "--help"
31
+ print_help(argv.first)
32
+ return 0
33
+ when "version", "-v", "--version"
34
+ puts EnvPact::VERSION
35
+ return 0
36
+ end
37
+
38
+ klass = COMMANDS[cmd]
39
+ unless klass
40
+ warn "envpact: unknown command '#{cmd}'"
41
+ warn ""
42
+ print_help
43
+ return 2
44
+ end
45
+
46
+ klass.new.run(argv)
47
+ rescue OptionParser::ParseError, UsageError => e
48
+ warn "envpact: #{e.message}"
49
+ 2
50
+ rescue EnvPact::Error, SystemCallError => e
51
+ warn "envpact: #{e.message}"
52
+ 1
53
+ end
54
+
55
+ private
56
+
57
+ def print_help(topic = nil)
58
+ if topic && (klass = COMMANDS[topic])
59
+ puts klass.new.help
60
+ return
61
+ end
62
+ puts global_help
63
+ end
64
+
65
+ def global_help
66
+ rows = COMMANDS.map { |n, k| [n, k.summary] }
67
+ rows << ["help", "Show help for a command"]
68
+ rows << ["version", "Show version"]
69
+ width = rows.map { |r| r[0].length }.max
70
+
71
+ lines = []
72
+ lines << "Usage: envpact <command> [options]"
73
+ lines << ""
74
+ lines << "Commands:"
75
+ rows.each { |name, summary| lines << format(" %-#{width}s %s", name, summary) }
76
+ lines << ""
77
+ lines << "Run `envpact help <command>` (or `envpact <command> -h`) for command-specific options."
78
+ lines << "Docs: https://github.com/repleadfy/envpact"
79
+ lines.join("\n")
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,50 @@
1
+ class EnvPact
2
+ # Minimal stdlib reader for .env files. Supports KEY=value, an optional
3
+ # `export ` prefix, comments, and single/double quoted values. No variable
4
+ # interpolation and no multiline values.
5
+ module Dotenv
6
+ LINE_RE = /\A\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)\z/.freeze
7
+ DOUBLE_QUOTE_ESCAPES = { "n" => "\n", '"' => '"', "\\" => "\\" }.freeze
8
+
9
+ # Files read for an env, in order; later files override earlier ones.
10
+ # .env.local is skipped for test so test runs don't depend on a
11
+ # developer's personal overrides (dotenv convention).
12
+ def self.files_for(env)
13
+ files = [".env", ".env.#{env}"]
14
+ files << ".env.local" unless env == "test"
15
+ files << ".env.#{env}.local"
16
+ files
17
+ end
18
+
19
+ def self.load(dir, env:)
20
+ files = []
21
+ values = {}
22
+ files_for(env).each do |name|
23
+ path = File.join(dir, name)
24
+ next unless File.file?(path)
25
+ files << name
26
+ values.merge!(parse(EnvPact.read_text(path)))
27
+ end
28
+ { files: files, values: values }
29
+ end
30
+
31
+ def self.parse(text)
32
+ EnvPact.utf8(text).sub(/\A/, "").each_line.each_with_object({}) do |raw, out|
33
+ m = LINE_RE.match(raw.chomp.chomp("\r"))
34
+ next unless m
35
+ out[m[1]] = parse_value(m[2].strip)
36
+ end
37
+ end
38
+
39
+ def self.parse_value(raw)
40
+ return "" if raw.start_with?("#") # `KEY= # comment` is an empty value
41
+ if raw.start_with?("'") && (close = raw.index("'", 1))
42
+ raw[1...close]
43
+ elsif raw.start_with?('"') && (m = raw.match(/\A"((?:[^"\\]|\\.)*)"/))
44
+ m[1].gsub(/\\(.)/) { DOUBLE_QUOTE_ESCAPES.fetch(Regexp.last_match(1), Regexp.last_match(0)) }
45
+ else
46
+ raw.sub(/\s+#.*\z/, "")
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,3 @@
1
+ class EnvPact
2
+ Entry = Struct.new(:type, :optional, :default, :enum_values, :line, keyword_init: true)
3
+ end
@@ -0,0 +1,20 @@
1
+ class EnvPact
2
+ class Error < StandardError; end
3
+
4
+ class ParseError < Error
5
+ attr_reader :line_no
6
+ def initialize(msg, line_no = nil)
7
+ super(line_no ? "line #{line_no}: #{msg}" : msg)
8
+ @line_no = line_no
9
+ end
10
+ end
11
+
12
+ class ValidationError < Error
13
+ attr_reader :result
14
+ def initialize(result)
15
+ @result = result
16
+ lines = ["env validation failed (env: #{result.env}):"] + result.errors.map { |p| " - #{p.message}" }
17
+ super(lines.join("\n"))
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,238 @@
1
+ # Parses env.spec files -- declarative contract for ConfigMap and Secret keys
2
+ # an app expects.
3
+ #
4
+ # Syntax (v5):
5
+ # KEY # str, required, configmap, shared (all envs)
6
+ # KEY? # optional
7
+ # KEY: int # typed (str|int|bool|url|enum(a,b))
8
+ # KEY: str = default # with default (configmap only)
9
+ #
10
+ # [secrets] # MODIFIER: type flips to secret (scope unchanged)
11
+ # [env: production] # SELECTOR: scope -> production, type RESETS to configmap
12
+ # [env: production, staging]# multi-env scope
13
+ # [shared] # SELECTOR: scope -> back to shared, type RESETS to configmap
14
+ #
15
+ # Output:
16
+ # configmap = { "*" => { "KEY" => Entry }, "production" => {...} }
17
+ # secrets = { "*" => { "DB_PASS" => Entry }, "production" => {...} }
18
+ class EnvPact
19
+ SHARED = "*".freeze
20
+ VALID_TYPES = %i[str int bool url enum].freeze
21
+ ENV_NAME_RE = /\A[A-Za-z0-9_-]+\z/.freeze
22
+
23
+ attr_reader :configmap, :secrets
24
+
25
+ def self.parse(text)
26
+ new.tap { |spec| spec.send(:_parse, text) }
27
+ end
28
+
29
+ def self.parse_file(path)
30
+ parse(EnvPact.read_text(path))
31
+ end
32
+
33
+ def initialize
34
+ @configmap = {}
35
+ @secrets = {}
36
+ end
37
+
38
+ # Returns array of env names declared in the spec (excluding "*").
39
+ def envs
40
+ (@configmap.keys + @secrets.keys).uniq.reject { |e| e == SHARED }.sort
41
+ end
42
+
43
+ # Returns merged keys (shared + given env) for configmap.
44
+ def configmap_for(env)
45
+ merge_scope(@configmap, env)
46
+ end
47
+
48
+ def secrets_for(env)
49
+ merge_scope(@secrets, env)
50
+ end
51
+
52
+ private
53
+
54
+ def merge_scope(bucket, env)
55
+ out = {}
56
+ out.merge!(bucket[SHARED]) if bucket[SHARED]
57
+ out.merge!(bucket[env]) if bucket[env]
58
+ out
59
+ end
60
+
61
+ def _parse(text)
62
+ scope = [SHARED]
63
+ type = :configmap
64
+
65
+ text = EnvPact.utf8(text).sub(/\A\uFEFF/, "")
66
+ text.each_line.with_index(1) do |raw, line_no|
67
+ line = strip_comment(raw.chomp).strip
68
+ next if line.empty?
69
+
70
+ if line.start_with?("[") && line.end_with?("]")
71
+ inner = line[1..-2].strip
72
+ if inner == "secrets"
73
+ type = :secret
74
+ elsif inner == "shared"
75
+ scope = [SHARED]
76
+ type = :configmap
77
+ elsif inner.start_with?("env:")
78
+ envs = inner.sub(/\Aenv:/, "").split(",").map(&:strip).reject(&:empty?)
79
+ raise ParseError.new("empty [env: ...] selector", line_no) if envs.empty?
80
+ envs.each do |e|
81
+ unless ENV_NAME_RE.match?(e)
82
+ raise ParseError.new(
83
+ "invalid env name '#{e}' in [env: ...] (must match #{ENV_NAME_RE.source}; use commas to separate envs)",
84
+ line_no
85
+ )
86
+ end
87
+ end
88
+ scope = envs
89
+ type = :configmap
90
+ else
91
+ raise ParseError.new("unknown header [#{inner}] (only [secrets], [shared] and [env: ...] allowed)", line_no)
92
+ end
93
+ next
94
+ end
95
+
96
+ entry = parse_key_line(line, line_no)
97
+ if type == :secret && !entry[:default].nil?
98
+ raise ParseError.new("secret '#{entry[:name]}' cannot have a default value", line_no)
99
+ end
100
+ # After the secret check, so a value mistakenly given to a secret is
101
+ # never echoed. Configmap defaults are not secret.
102
+ check_default_type(entry, line_no)
103
+
104
+ store_entry(type, scope, entry, line_no)
105
+ end
106
+ end
107
+
108
+ def parse_key_line(line, line_no)
109
+ m = line.match(/\A([A-Z][A-Z0-9_]*)(\?)?(?:\s*:\s*([a-z]+(?:\([^)]*\))?))?(?:\s*=\s*(.+))?\z/)
110
+ # The line itself is not echoed: it may hold a value pasted by mistake.
111
+ raise ParseError.new("invalid key line (expected KEY, KEY?, KEY: type, KEY = default)", line_no) unless m
112
+
113
+ name = m[1]
114
+ optional = !m[2].nil?
115
+ type_str = m[3] || "str"
116
+ default = m[4] && parse_default(name, m[4].strip, line_no)
117
+
118
+ type, enum_values = parse_type(type_str, line_no)
119
+ { name: name, type: type, optional: optional, default: default, enum_values: enum_values }
120
+ end
121
+
122
+ # A "#" starts a comment at line start or after whitespace, never inside a
123
+ # double-quoted default.
124
+ def strip_comment(line)
125
+ in_quotes = false
126
+ escaped = false
127
+ line.each_char.with_index do |ch, i|
128
+ if escaped
129
+ escaped = false
130
+ elsif ch == "\\" && in_quotes
131
+ escaped = true
132
+ elsif ch == "\""
133
+ in_quotes = !in_quotes
134
+ elsif ch == "#" && !in_quotes && (i.zero? || line[i - 1] =~ /\s/)
135
+ return line[0...i]
136
+ end
137
+ end
138
+ line
139
+ end
140
+
141
+ # Only \" and \\ are escapes; any other backslash is kept as is.
142
+ def parse_default(name, raw, line_no)
143
+ return raw unless raw.start_with?("\"")
144
+ m = raw.match(/\A"((?:[^"\\]|\\.)*)"\z/)
145
+ raise ParseError.new("unterminated quoted default for '#{name}'", line_no) unless m
146
+ m[1].gsub(/\\([\\"])/) { Regexp.last_match(1) }
147
+ end
148
+
149
+ def check_default_type(entry, line_no)
150
+ default = entry[:default]
151
+ return if default.nil? || Types.valid?(default, entry[:type], entry[:enum_values])
152
+ reason = Message.invalid_reason(entry[:type], entry[:enum_values])
153
+ raise ParseError.new("default #{default.inspect} for '#{entry[:name]}' #{reason}", line_no)
154
+ end
155
+
156
+ def parse_type(type_str, line_no)
157
+ if type_str.start_with?("enum(")
158
+ unless (em = type_str.match(/\Aenum\((.+)\)\z/))
159
+ raise ParseError.new("malformed enum type: #{type_str}", line_no)
160
+ end
161
+ values = em[1].split(",").map(&:strip).reject(&:empty?)
162
+ raise ParseError.new("enum requires at least one value", line_no) if values.empty?
163
+ [:enum, values]
164
+ else
165
+ sym = type_str.to_sym
166
+ unless VALID_TYPES.include?(sym)
167
+ raise ParseError.new("unknown type '#{type_str}' (valid: #{VALID_TYPES.join(', ')})", line_no)
168
+ end
169
+ [sym, nil]
170
+ end
171
+ end
172
+
173
+ def store_entry(type, scope, e, line_no)
174
+ bucket = (type == :secret ? @secrets : @configmap)
175
+ other = (type == :secret ? @configmap : @secrets)
176
+
177
+ scope.each do |env|
178
+ bucket[env] ||= {}
179
+
180
+ if (clash = find_overlapping(other, env, e[:name]))
181
+ cm_line, secret_line = type == :secret ? [clash[:entry].line, line_no] : [line_no, clash[:entry].line]
182
+ raise ParseError.new(
183
+ "key '#{e[:name]}' declared as both configmap (line #{cm_line}) and secret (line #{secret_line})",
184
+ line_no
185
+ )
186
+ end
187
+
188
+ if (existing = find_overlapping(bucket, env, e[:name]))
189
+ raise ParseError.new(
190
+ "key '#{e[:name]}' defined in overlapping scopes ('#{existing[:env]}' line #{existing[:entry].line} and '#{env}' here)",
191
+ line_no
192
+ )
193
+ end
194
+
195
+ bucket[env][e[:name]] = Entry.new(
196
+ type: e[:type],
197
+ optional: e[:optional],
198
+ default: e[:default],
199
+ enum_values: e[:enum_values],
200
+ line: line_no
201
+ )
202
+ end
203
+
204
+ check_cross_env_type_consistency(bucket, e[:name], e[:type], e[:enum_values], line_no)
205
+ end
206
+
207
+ def find_overlapping(bucket, env, key)
208
+ bucket.each do |existing_env, keys|
209
+ next unless keys.key?(key)
210
+ next if existing_env == env
211
+ if existing_env == SHARED || env == SHARED
212
+ return { env: existing_env, entry: keys[key] }
213
+ end
214
+ end
215
+ if bucket[env] && bucket[env].key?(key)
216
+ return { env: env, entry: bucket[env][key] }
217
+ end
218
+ nil
219
+ end
220
+
221
+ def check_cross_env_type_consistency(bucket, key, type, enum_values, line_no)
222
+ seen = nil
223
+ bucket.each do |env, keys|
224
+ next unless keys.key?(key)
225
+ e = keys[key]
226
+ if seen.nil?
227
+ seen = [env, e.type, e.enum_values]
228
+ else
229
+ if seen[1] != e.type || seen[2] != e.enum_values
230
+ raise ParseError.new(
231
+ "key '#{key}' has different types across envs ('#{seen[0]}' is #{seen[1]}, '#{env}' is #{e.type})",
232
+ line_no
233
+ )
234
+ end
235
+ end
236
+ end
237
+ end
238
+ end
@@ -0,0 +1,40 @@
1
+ class EnvPact
2
+ # One thing wrong with a set of values checked against a spec.
3
+ #
4
+ # kind is :missing, :invalid or :extra. value is the offending value for
5
+ # configmap keys only -- it is always nil for secrets and extras, so a
6
+ # Problem can be printed or logged without leaking a secret.
7
+ Problem = Struct.new(:kind, :key, :secret, :line, :value, :type, :enum_values, keyword_init: true) do
8
+ def message
9
+ Message.format(self)
10
+ end
11
+ end
12
+
13
+ # Builds problem text. Pass value: explicitly to reveal a secret value
14
+ # (the CLI does this for --show-values); by default the problem's own,
15
+ # already-masked value is used.
16
+ module Message
17
+ BOOL_HINT = "(expected true/false/1/0/yes/no)".freeze
18
+
19
+ def self.format(problem, value: problem.value)
20
+ key = problem.key
21
+ case problem.kind
22
+ when :missing
23
+ "missing required env var '#{key}' (declared at line #{problem.line})"
24
+ when :extra
25
+ "unknown env var '#{key}' (not declared in spec)"
26
+ when :invalid
27
+ subject = value.nil? ? "env var '#{key}' (secret)" : "env var '#{key}' = #{value.inspect}"
28
+ "#{subject} #{invalid_reason(problem.type, problem.enum_values)}"
29
+ end
30
+ end
31
+
32
+ def self.invalid_reason(type, enum_values)
33
+ case type
34
+ when :bool then "is not a valid bool #{BOOL_HINT}"
35
+ when :enum then "is not in enum(#{enum_values.join(', ')})"
36
+ else "is not a valid #{type}"
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,17 @@
1
+ class EnvPact
2
+ # Outcome of EnvPact#check. ok? ignores warnings.
3
+ class Result
4
+ attr_reader :env, :errors, :warnings, :applied_sections
5
+
6
+ def initialize(env:, errors:, warnings:, applied_sections:)
7
+ @env = env
8
+ @errors = errors
9
+ @warnings = warnings
10
+ @applied_sections = applied_sections
11
+ end
12
+
13
+ def ok?
14
+ @errors.empty?
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,67 @@
1
+ # Task: build or update this repo's env.spec
2
+
3
+ You are working in a code repository. Produce `env.spec` at the repo root: the
4
+ env var contract for this app, checked by `envpact` locally, before deploy and at
5
+ boot. The contract lists **names, types and rules only — never values.**
6
+
7
+ ## 1. Discover every env var the app reads
8
+
9
+ Search the whole repo, in every language and place, for example:
10
+
11
+ - Code: Ruby `ENV["X"]`, `ENV.fetch("X", ...)`; Python `os.environ[...]`,
12
+ `os.environ.get`, `os.getenv`; JS/TS `process.env.X`, `import.meta.env.X`;
13
+ Go `os.Getenv`, `os.LookupEnv`; shell `$X`, `${X:-default}`; framework config
14
+ (Rails `config/*.yml` with ERB, `config/initializers`, settings modules).
15
+ - Dockerfiles (`ENV`, `ARG`), docker-compose files, CI workflows.
16
+ - Deploy config: `kdep/*/app.yml` (`configmap:` keys and values),
17
+ `kdep/*/secrets.yml` (key names only), Helm values.
18
+ - `.env*` files and `.env.example` — **key names only**.
19
+ - README and docs that tell people which vars to set.
20
+
21
+ Ignore vars the runtime provides by itself (`PATH`, `HOME`, `PWD`, `HOSTNAME`,
22
+ etc.) unless the app clearly depends on them.
23
+
24
+ **Hard rule: never copy values into the contract or the transcript.** Do not print, quote or
25
+ summarize the contents of `.env*`, `secrets.yml` or any credential. Read them only
26
+ to learn key names.
27
+
28
+ ## 2. Classify each var
29
+
30
+ - **Secret or ConfigMap:** passwords, tokens, API keys, private keys, connection
31
+ strings with credentials → `[secrets]`. Everything else → ConfigMap.
32
+ - **Type:** `int`, `bool`, `url` or `enum(...)` when the code parses or compares
33
+ it that way; otherwise `str`.
34
+ - **Optional (`?`):** the code tolerates absence (fallback, `fetch` default,
35
+ `|| default`, feature off when unset). Otherwise required.
36
+ - **Default (`= value`):** only literal, non-secret defaults that the code itself
37
+ uses. Never invent one.
38
+ - **Scope:** shared unless the var is clearly specific to some envs (e.g. only in
39
+ production config or only in `app_<env>.yml`) → `[env: name]` section.
40
+
41
+ ## 3. Write env.spec
42
+
43
+ Use exactly this syntax:
44
+
45
+ {{SYNTAX}}
46
+
47
+ Put shared keys on top. Group related keys with a short comment. If `env.spec`
48
+ already exists, update it in place: keep its comments and existing decisions, add
49
+ what is missing, and never silently drop a key — if a declared key looks unused,
50
+ keep it and flag it.
51
+
52
+ ## 4. Flag what you are unsure about
53
+
54
+ Above any key whose classification is a guess, add a comment:
55
+
56
+ ```
57
+ # TODO(envpact): looks like a secret (used as Authorization header) — confirm
58
+ API_TOKEN
59
+ ```
60
+
61
+ ## 5. Validate and report
62
+
63
+ Run `envpact lint` and fix the file until it passes. Then report, briefly:
64
+
65
+ - how many vars you found and where (by file, no values);
66
+ - each `# TODO(envpact):` decision;
67
+ - declared keys that appear unused.
@@ -0,0 +1,17 @@
1
+ class EnvPact
2
+ # Instructions for an AI agent to build or update a repo's env.spec. The
3
+ # template and the syntax reference ship with the gem, so the prompt always
4
+ # matches the parser it was released with.
5
+ module ScanPrompt
6
+ DIR = __dir__
7
+
8
+ def self.render
9
+ template = File.read(File.join(DIR, "scan_prompt.md"))
10
+ template.sub("{{SYNTAX}}") { syntax.chomp }
11
+ end
12
+
13
+ def self.syntax
14
+ File.read(File.join(DIR, "syntax.md"))
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,44 @@
1
+ ```
2
+ # shared (all envs) -- the top of the file is the default for every env
3
+ APP_NAME
4
+ LOG_LEVEL: enum(debug, info, warn, error) = info
5
+ DEBUG?: bool
6
+ PORT: int = 3000
7
+ PUBLIC_URL: url
8
+
9
+ [secrets]
10
+ DB_PASS
11
+ OPENAI_API_KEY
12
+
13
+ [env: production]
14
+ SENTRY_DSN: url
15
+ [secrets]
16
+ STRIPE_LIVE_KEY
17
+
18
+ [env: production, staging]
19
+ CDN_HOST
20
+
21
+ [shared]
22
+ FEATURE_FLAGS?
23
+ ```
24
+
25
+ - `KEY` — required string, ConfigMap, in the current scope.
26
+ - `KEY?` — optional.
27
+ - `KEY: type` — `str` (default) | `int` | `bool` | `url` | `enum(a, b, c)`.
28
+ - `bool` accepts `true false 1 0 yes no` (any case).
29
+ - `url` needs a scheme and a host: `postgres://u:p@h:5432/db`, `https://x.y`.
30
+ - `KEY = default` — default value, ConfigMap only; secrets cannot have defaults.
31
+ The default must be valid for the type (`PORT: int = 3OOO` is a lint error).
32
+ Quote it to keep `#` or surrounding spaces: `GREETING = "hi # there "`
33
+ (only `\"` and `\\` are escapes; any other backslash is kept).
34
+ - `[secrets]` — modifier: following keys are Secrets; scope unchanged.
35
+ - `[env: name]` / `[env: a, b]` — selector: following keys apply only to those
36
+ envs; type resets to ConfigMap. Env names are free-form (`[A-Za-z0-9_-]+`).
37
+ - `[shared]` — selector: back to the shared scope (all envs); type resets to
38
+ ConfigMap.
39
+ - `#` starts a comment at the start of a line or after whitespace
40
+ (`URL = http://x/a#frag` keeps the `#frag`).
41
+ - An env with no `[env: …]` section gets only the shared keys. A key may not be
42
+ declared in overlapping scopes, may not be both ConfigMap and Secret, and must
43
+ have the same type in every env.
44
+ - Empty values count as absent.
@@ -0,0 +1,38 @@
1
+ require "uri"
2
+
3
+ class EnvPact
4
+ BOOL_VALUES = %w[true false 1 0 yes no].freeze
5
+
6
+ # Value validation shared by the checker (values) and the parser (defaults).
7
+ module Types
8
+ def self.valid?(raw, type, enum_values = nil)
9
+ case type
10
+ when :str then true
11
+ when :int then !Integer(raw, 10).nil?
12
+ when :bool then BOOL_VALUES.include?(raw.downcase)
13
+ when :enum then enum_values.include?(raw)
14
+ when :url then valid_url?(raw)
15
+ end
16
+ rescue ArgumentError
17
+ false
18
+ end
19
+
20
+ def self.valid_url?(raw)
21
+ uri = URI.parse(raw)
22
+ !uri.scheme.nil? && !uri.host.nil? && !uri.host.empty?
23
+ rescue URI::InvalidURIError
24
+ false
25
+ end
26
+ end
27
+
28
+ # Reads a text file as UTF-8 whatever the process locale, dropping a BOM.
29
+ def self.read_text(path)
30
+ File.read(path, mode: "r:BOM|UTF-8")
31
+ end
32
+
33
+ # Text handed to the parsers may come tagged US-ASCII or binary (e.g. under
34
+ # LANG=C); treat it as UTF-8 so non-ASCII comments don't crash matching.
35
+ def self.utf8(text)
36
+ text.encoding == Encoding::UTF_8 ? text : text.dup.force_encoding(Encoding::UTF_8)
37
+ end
38
+ end
@@ -0,0 +1,3 @@
1
+ class EnvPact
2
+ VERSION = "0.1.0".freeze
3
+ end
data/lib/envpact.rb ADDED
@@ -0,0 +1,11 @@
1
+ require_relative "envpact/version"
2
+ require_relative "envpact/errors"
3
+ require_relative "envpact/entry"
4
+ require_relative "envpact/parser"
5
+ require_relative "envpact/types"
6
+ require_relative "envpact/problem"
7
+ require_relative "envpact/result"
8
+ require_relative "envpact/checker"
9
+ require_relative "envpact/dotenv"
10
+ require_relative "envpact/scan_prompt"
11
+ require_relative "envpact/cli"
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: envpact
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Leadfy
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-11-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: minitest
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '5.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ description: 'Parses env.spec files: a declarative contract describing which env vars
56
+ an app expects, their types, optionality, and ConfigMap-vs-Secret classification.
57
+ Pure stdlib, zero runtime dependencies.'
58
+ email:
59
+ - dev@leadfy.com
60
+ executables:
61
+ - envpact
62
+ extensions: []
63
+ extra_rdoc_files: []
64
+ files:
65
+ - CHANGELOG.md
66
+ - LICENSE.txt
67
+ - README.md
68
+ - exe/envpact
69
+ - lib/envpact.rb
70
+ - lib/envpact/checker.rb
71
+ - lib/envpact/cli.rb
72
+ - lib/envpact/cli/check.rb
73
+ - lib/envpact/cli/command.rb
74
+ - lib/envpact/cli/exec.rb
75
+ - lib/envpact/cli/lint.rb
76
+ - lib/envpact/cli/scan_prompt.rb
77
+ - lib/envpact/dotenv.rb
78
+ - lib/envpact/entry.rb
79
+ - lib/envpact/errors.rb
80
+ - lib/envpact/parser.rb
81
+ - lib/envpact/problem.rb
82
+ - lib/envpact/result.rb
83
+ - lib/envpact/scan_prompt.md
84
+ - lib/envpact/scan_prompt.rb
85
+ - lib/envpact/syntax.md
86
+ - lib/envpact/types.rb
87
+ - lib/envpact/version.rb
88
+ homepage: https://github.com/repleadfy/envpact
89
+ licenses:
90
+ - MIT
91
+ metadata: {}
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: 2.5.0
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubygems_version: 3.5.19
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: 'Env var contract for apps: one file, checked locally, before deploy and
111
+ at boot'
112
+ test_files: []