summaryrefslogtreecommitdiff
path: root/controllers/cartridges.rb
blob: df474a90ae9f977491adda04b8a1430a4758f84b (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
# frozen_string_literal: true

require_relative '../components/storage'
require_relative '../logic/helpers/hash'
require_relative '../logic/cartridge/default'

module NanoBot
  module Controllers
    class Cartridges
      def self.all
        files = {}

        path = Components::Storage.cartridges_path

        Dir.glob("#{path}/**/*.{yml,yaml}").each do |file|
          files[Pathname.new(file).realpath] = {
            base: path,
            path: Pathname.new(file).realpath
          }
        end

        cartridges = []

        files.values.uniq.map do |file|
          cartridge = Logic::Helpers::Hash.symbolize_keys(
            YAML.safe_load_file(file[:path], permitted_classes: [Symbol])
          ).merge({
                    system: {
                      id: file[:path].to_s.sub(/^#{Regexp.escape(file[:base])}/, '').sub(%r{^/}, '').sub(/\.[^.]+\z/,
                                                                                                         ''),
                      path: file[:path],
                      base: file[:base]
                    }
                  })

          next if cartridge[:meta][:name].nil?

          cartridges << cartridge
        rescue StandardError => _e
        end

        cartridges = cartridges.sort_by { |cartridge| cartridge[:meta][:name] }

        cartridges.prepend(
          { system: { id: '-' }, meta: { name: 'Default', symbol: '🤖' } }
        )

        cartridges
      end
    end
  end
end