summaryrefslogtreecommitdiff
path: root/controllers/cartridges.rb
blob: 7215a993f263d15b6cbb38645e1b4fb7a2d12da7 (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
53
54
55
56
57
58
# frozen_string_literal: true

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

module NanoBot
  module Controllers
    class Cartridges
      def self.load(path)
        Logic::Cartridge::Parser.parse(File.read(path), format: File.extname(path))
      end

      def self.all
        files = {}

        path = Components::Storage.cartridges_path

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

        cartridges = []

        files.values.uniq.map do |file|
          cartridge = load_cartridge(file[:path]).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