Module: Above::Config

Defined in:
lib/above/config.rb

Overview

Persist & use configuration

Class Method Summary collapse

Class Method Details

.config_dirObject



11
12
13
# File 'lib/above/config.rb', line 11

def config_dir
  File.join(Utils.home_dir, ".config/above")
end

.domains_dirObject



15
16
17
# File 'lib/above/config.rb', line 15

def domains_dir
  File.join(Config.config_dir, "domains")
end

.exemplarObject



19
20
21
22
23
24
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
50
51
52
53
54
55
56
# File 'lib/above/config.rb', line 19

def exemplar
  {
    "server" => {
      "domain" => "localhost",
      "ip" => "0.0.0.0",
      "max_fibers" => 20,
      "port" => 1965,
      "tls_cert" => "/home/above/localhost.crt",
      "tls_key" => "/home/above/localhost.key"
    },
    "middleware" => {
      "Above::MiddleWare::Block" => {
        "blocklist" => [
          "192.168.2.0/24"
        ]
      },
      "Above::MiddleWare::Cache" => {
        "max_size" => 12
      },
      "Above::MiddleWare::Log" => {
        "log_file" => "localhost.log"
      },
      "Above::MiddleWare::Redirect" => {
        "redirect_permanent" => {
          "/from" => "/to"
        },
        "redirect_temporary" => {
          "/from" => "/to"
        }
      },
      "Above::MiddleWare::Static" => {
        "docroot" => "/home/above/www",
        "index" => "index.gmi",
        "lang" => "en"
      }
    }
  }
end

.init_dirObject



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/above/config.rb', line 58

def init_dir
  unless File.exist?(Config.domains_dir)
    FileUtils.mkdir_p(Config.domains_dir)
    File.write(File.join(Config.config_dir, "example.yml"), Config.exemplar.to_yaml)
    puts "Configuration directory created"
  end
  if Dir.empty?(Config.domains_dir)
    puts "No configuration files found"
    exit
  end
end

.read_config(dir: nil) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/above/config.rb', line 70

def read_config(dir: nil)
  dir ||= Config.domains_dir
  files = Dir[File.join(dir, "*.yml")] # not subfolders
  domains = {}
  files.each do |file|
    hash = YAML.safe_load_file(file, permitted_classes: [Hash])
    Utils.check_keys(expected_keys: Config.exemplar.keys, file:, hash:)
    Utils.check_keys(expected_keys: Config.exemplar["server"].keys, file:, hash: hash["server"])
    # Middleware config to be checked in each piece of middleware
    domains[hash["server"]["domain"]] = hash
  end
  if domains.size == 0
    puts "No configuration files found"
    exit
  end
  domains
end