Class: Dev::Env

Inherits:
Object show all
Defined in:
lib/firespring_dev_commands/env.rb

Overview

Class instance represents a ‘.env’ file and includes methods to read/write the given filename

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = '.env') ⇒ Env

Returns a new instance of Env.



8
9
10
11
12
13
14
15
16
17
# File 'lib/firespring_dev_commands/env.rb', line 8

def initialize(filename = '.env')
  @envfile = Pathname.new(filename)
  @data = {}
  return unless File.exist?(@envfile)

  File.readlines(@envfile).each do |line|
    key, value = line.split('=')
    @data[key.to_s.strip.to_sym] = value.to_s.strip
  end
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



6
7
8
# File 'lib/firespring_dev_commands/env.rb', line 6

def data
  @data
end

#envfileObject

Returns the value of attribute envfile.



6
7
8
# File 'lib/firespring_dev_commands/env.rb', line 6

def envfile
  @envfile
end

Instance Method Details

#containerized?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/firespring_dev_commands/env.rb', line 38

def containerized?
  # Fast path: common flags files
  return true if File.exist?('/.dockerenv')            # Docker
  return true if File.exist?('/run/.containerenv')     # Podman / some runtimes

  # Env flags some images set
  return true if ENV['DOCKER_CONTAINER'] == 'true'
  return true if ENV['container']&.match?(/docker|podman|lxc|containerd/i)

  # cgroup hints (docker, containerd, kubernetes, podman)
  %w(/proc/1/cgroup /proc/self/cgroup).any? do |p|
    next false unless File.readable?(p)

    File.read(p).match?(/docker|containerd|kubepods|podman|libpod/i)
  end
rescue
  false
end

#get(key) ⇒ Object

Get the value of the key from the loaded env data



20
21
22
# File 'lib/firespring_dev_commands/env.rb', line 20

def get(key)
  data[key.to_s.strip.to_sym]
end

#on_hostObject



57
58
59
# File 'lib/firespring_dev_commands/env.rb', line 57

def on_host
  yield unless containerized?
end

#set(key, value) ⇒ Object

Set the value of the key in the loaded env data



25
26
27
# File 'lib/firespring_dev_commands/env.rb', line 25

def set(key, value)
  data[key.to_s.strip.to_sym] = value.to_s.strip
end

#writeObject

Write the current env data back to the original file



30
31
32
33
34
35
36
# File 'lib/firespring_dev_commands/env.rb', line 30

def write
  File.open(envfile, 'w') do |file|
    data.each do |key, value|
      file.write("#{key}=#{value}\n")
    end
  end
end