service/src/service/service_definition.cr

94 lines
2.3 KiB
Crystal

require "yaml"
require "specparser"
class ServiceDefinition
struct Consumes
getter token : String
def initialize(@token)
@optional = false
if @token.match /\?$/
@token = @token.gsub /\?$/, ""
@optional = true
end
end
end
struct Provides
getter token : String
def initialize(@token)
end
end
struct Hook
getter name : String
getter command : String
getter unless_directory : String?
getter unless_file : String?
def initialize(@name, @command, @unless_file = nil, @unless_directory = nil)
end
def initialize(section : SpecParser::Section)
@name = section.content["name"].as_s
@command = section.content["command"].as_s
@unless_directory = section.content["unless-directory"]?
.try &.as_s
@unless_file = section.content["unless-file"]?.try &.as_s
end
end
class_getter all = [] of ServiceDefinition
getter name : String
getter command : String
getter stop_command : String?
getter directory : String?
getter user : String?
getter provides : String?
getter consumes : Array(Consumes)
getter environment_variables : Array(String)
getter pre_start_hooks : Array(Hook)
getter provides : Array(Provides)
def initialize(@name, specs : SpecParser)
sections = specs.sections
specs = specs.assignments
@command = specs["command"].as_s
@stop_command = specs["stop-command"]?.try &.as_s
@directory = specs["directory"]?.try &.as_s
@user = specs["user"]?.try &.as_s
@provides = specs["provides"]?.try &.as_a_or_s.map { |x| Provides.new x } || Array(Provides).new
@consumes = specs["consumes"]?.try &.as_a_or_s.map { |x| Consumes.new x } || Array(Consumes).new
@environment_variables = specs["environment-variables"]?.try &.as_a_or_s || Array(String).new
@pre_start_hooks = sections.select(&.name.== "pre-start").map { |x| Hook.new x } || Array(Hook).new
end
def self.load(path)
Dir.each_child path do |child|
if child.match /\.spec$/
name = File.basename(child, ".spec")
specs = SpecParser.parse File.read "#{path}/#{child}"
@@all << ServiceDefinition.new name, specs
else
next
end
end
end
def self.get(name) : ServiceDefinition
_def = @@all.find &.name.==(name)
if _def.nil?
raise ::Service::Exception.new "Service '#{name}' does not exist."
end
_def
end
def to_s
name
end
end