Class: Mxup::EnvFile

Inherits:
Object
  • Object
show all
Defined in:
lib/mxup/env_file.rb

Overview

Reads, validates, and scaffolds the <config-name>.env file that supplies values for the config's required_env vars.

The file is a plain dotenv-style KEY=value list. mxup up checks every declared required var has a non-empty value here before starting anything; the values themselves reach each window because the launcher script sources this file (see Launcher#build_script).

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ EnvFile

Returns a new instance of EnvFile.



12
13
14
15
# File 'lib/mxup/env_file.rb', line 12

def initialize(config)
  @config = config
  @path   = config.env_file_path
end

Instance Method Details

#missingObject

Required vars that are still missing a value (key absent, or value blank).



18
19
20
21
# File 'lib/mxup/env_file.rb', line 18

def missing
  values = parse
  @config.required_env.reject { |rv| present?(values[rv.name]) }
end

#parse(contents = nil) ⇒ Object

Parse the file (or a given string) into a { KEY => value } hash. Blank lines and # comments are skipped; surrounding quotes are stripped.



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mxup/env_file.rb', line 53

def parse(contents = nil)
  contents ||= File.exist?(@path) ? File.read(@path) : ''
  contents.each_line.each_with_object({}) do |line, acc|
    line = line.strip
    next if line.empty? || line.start_with?('#')

    key, sep, value = line.partition('=')
    next if sep.empty? || key.strip.empty?

    acc[key.strip] = unquote(value.strip)
  end
end

#scaffold!Object

Create the file, or append entries for any required vars not yet present as keys. Existing content and values are preserved. Returns the path.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mxup/env_file.rb', line 25

def scaffold!
  existing = File.exist?(@path) ? File.read(@path) : nil
  existing = nil if existing && existing.strip.empty?

  present_keys = parse(existing || '').keys
  additions    = @config.required_env.reject { |rv| present_keys.include?(rv.name) }
  return @path if additions.empty? && existing

  parts = []
  parts << if existing
             existing.rstrip
           else
             "# Required environment variables for mxup.\n" \
             '# Fill in the values below, then re-run `mxup up`.'
           end
  additions.each do |rv|
    block = []
    block << "# #{rv.description}" if rv.description && !rv.description.empty?
    block << "#{rv.name}="
    parts << block.join("\n")
  end

  File.write(@path, parts.join("\n\n") + "\n")
  @path
end