Sha256: 4ab4e70e28ed2d7e1876fd229d872aa689fa4611632c6e67bc0c47b652d2f727

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module Joi
  class Runner
    attr_reader :root_dir, :watchers, :preset

    def initialize(
      options:,
      root_dir: Dir.pwd,
      preset: Presets::Default.new(self, options)
    )
      @root_dir = Pathname.new(root_dir)
      @watchers = []
      @preset = preset
    end

    def run_all
      watchers.each {|watcher| watcher[:thread]&.kill }
      preset.run_all
    end

    def start
      preset.register
      run_all

      listener = Listen.to(
        root_dir.to_s,
        ignore: [%r{(public|node_modules|assets|vendor)/}]
      ) do |modified, added, removed|
        modified = convert_to_relative_paths(modified)
        added = convert_to_relative_paths(added)
        removed = convert_to_relative_paths(removed)

        watchers.each do |watcher|
          run_watcher(
            watcher,
            modified: modified,
            added: added,
            removed: removed
          )
        end
      end

      listener.start

      sleep
    end

    def run_watcher(watcher, modified:, added:, removed:)
      paths = []
      paths += modified if watcher[:on].include?(:modified)
      paths += added if watcher[:on].include?(:added)
      paths += removed if watcher[:on].include?(:removed)
      paths = paths.select do |path|
        watcher[:pattern].any? {|pattern| path.to_s.match?(pattern) }
      end

      return unless paths.any?

      watcher[:thread]&.kill
      watcher[:thread] = Thread.new { watcher[:command].call(paths) }
    end

    def watch(watcher)
      watchers << watcher
    end

    def convert_to_relative_paths(paths)
      paths.map {|file| Pathname.new(file).relative_path_from(root_dir) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
joi-0.0.2 lib/joi/runner.rb