summaryrefslogtreecommitdiff
path: root/vendor/bundle/ruby/3.4.0/gems/sass-embedded-1.101.0-arm64-darwin/lib/sass/compiler/connection.rb
blob: 50c722a7f9366bb5225042819e39cd22e412d4e7 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# frozen_string_literal: true

require 'open3'

require 'sass/cli'

module Sass
  class Compiler
    # The stdio based {Connection} between the {Dispatcher} and the compiler.
    #
    # It runs the `sass --embedded` command.
    class Connection
      def initialize
        @mutex = Mutex.new
        @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(*CLI::COMMAND, '--embedded', chdir: __dir__)

        @stdin.binmode

        # # https://dart.dev/tools/dart-devtools
        # if %w[dart dartvm].include?(File.basename(CLI::COMMAND.first, '.exe')) &&
        #    %w[--enable-vm-service --observe].intersect?(CLI::COMMAND.map { |argument| argument.partition('=').first })
        #   Kernel.warn(@stdout.readline, uplevel: 0)
        #   Kernel.warn(@stdout.readline, uplevel: 0)
        # end

        @stdout.binmode

        @wait_thread.name = "sass-embedded-process-waiter-#{id}"
      end

      def id
        @wait_thread.pid
      end

      def listen(dispatcher)
        Thread.new do
          Thread.current.name = "sass-embedded-process-stdout-poller-#{id}"
          loop do
            length = Varint.read(@stdout)
            id = Varint.read(@stdout)
            proto = @stdout.read(length - Varint.length(id))
            dispatcher.receive_proto(id, proto)
          end
        rescue IOError, Errno::EBADF, Errno::EPROTO => e
          dispatcher.error(e)
          @mutex.synchronize do
            @stdout.close
          end
        end

        Thread.new do
          Thread.current.name = "sass-embedded-process-stderr-poller-#{id}"
          loop do
            Kernel.warn(@stderr.readline, uplevel: 0)
          end
        rescue IOError, Errno::EBADF
          @mutex.synchronize do
            @stderr.close
          end
        end
      end

      def close
        @mutex.synchronize do
          @stdin.close
          @wait_thread.join
          @stdout.close
          @stderr.close
        end
      end

      def closed?
        @mutex.synchronize do
          @stdin.closed? && !@wait_thread.alive?
        end
      end

      def write(id, proto)
        buffer = []
        Varint.write(buffer, Varint.length(id) + proto.length)
        Varint.write(buffer, id)
        @mutex.synchronize do
          @stdin.write(buffer.pack('C*'), proto)
        end
      end
    end

    private_constant :Connection
  end
end