Class: Steep::Drivers::Watch

Inherits:
Object
  • Object
show all
Includes:
Utils::DriverHelper
Defined in:
lib/steep/drivers/watch.rb

Constant Summary collapse

LSP =
LanguageServer::Protocol

Instance Attribute Summary collapse

Attributes included from Utils::DriverHelper

#disable_install_collection, #steepfile

Instance Method Summary collapse

Methods included from Utils::DriverHelper

#install_collection, #keep_diagnostic?, #load_config, #request_id, #shutdown_exit, #wait_for_message, #wait_for_response_id

Constructor Details

#initialize(stdout:, stderr:) ⇒ Watch

Returns a new instance of Watch.



15
16
17
18
19
20
21
22
# File 'lib/steep/drivers/watch.rb', line 15

def initialize(stdout:, stderr:)
  @dirs = []
  @stdout = stdout
  @stderr = stderr
  @queue = Thread::Queue.new
  @severity_level = :warning
  @jobs_option = Utils::JobsOption.new()
end

Instance Attribute Details

#dirsObject (readonly)

Returns the value of attribute dirs.



4
5
6
# File 'lib/steep/drivers/watch.rb', line 4

def dirs
  @dirs
end

#jobs_optionObject (readonly)

Returns the value of attribute jobs_option.



9
10
11
# File 'lib/steep/drivers/watch.rb', line 9

def jobs_option
  @jobs_option
end

#queueObject (readonly)

Returns the value of attribute queue.



7
8
9
# File 'lib/steep/drivers/watch.rb', line 7

def queue
  @queue
end

#severity_levelObject

Returns the value of attribute severity_level.



8
9
10
# File 'lib/steep/drivers/watch.rb', line 8

def severity_level
  @severity_level
end

#stderrObject (readonly)

Returns the value of attribute stderr.



6
7
8
# File 'lib/steep/drivers/watch.rb', line 6

def stderr
  @stderr
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



5
6
7
# File 'lib/steep/drivers/watch.rb', line 5

def stdout
  @stdout
end

Instance Method Details

#runObject



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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/steep/drivers/watch.rb', line 28

def run()
  if dirs.empty?
    stdout.puts "Specify directories to watch"
    return 1
  end

  project = load_config()

  client_read, server_write = IO.pipe
  server_read, client_write = IO.pipe

  client_reader = LanguageServer::Protocol::Transport::Io::Reader.new(client_read)
  client_writer = LanguageServer::Protocol::Transport::Io::Writer.new(client_write)

  server_reader = LanguageServer::Protocol::Transport::Io::Reader.new(server_read)
  server_writer = LanguageServer::Protocol::Transport::Io::Writer.new(server_write)

  typecheck_workers = Server::WorkerProcess.start_typecheck_workers(steepfile: project.steepfile_path, args: dirs.map(&:to_s), steep_command: jobs_option.steep_command, count: jobs_option.jobs_count_value)

  master = Server::Master.new(
    project: project,
    reader: server_reader,
    writer: server_writer,
    interaction_worker: nil,
    typecheck_workers: typecheck_workers
  )
  master.typecheck_automatically = false
  master.commandline_args.push(*dirs.map(&:to_s))

  main_thread = Thread.start do
    master.start()
  end

  initialize_id = request_id()
  client_writer.write(method: "initialize", id: initialize_id, params: DEFAULT_CLI_LSP_INITIALIZE_PARAMS)
  wait_for_response_id(reader: client_reader, id: initialize_id)

  Steep.logger.info "Watching #{dirs.join(", ")}..."

  watch_paths = dirs.map do |dir|
    case
    when dir.directory?
      dir.realpath
    when dir.file?
      dir.parent.realpath
    else
      dir
    end
  end

  dir_paths = Set.new(dirs.select(&:directory?).map(&:realpath))
  file_paths = Set.new(dirs.select(&:file?).map(&:realpath))

  listener = Listen.to(*watch_paths.map(&:to_s)) do |modified, added, removed|
    stdout.print Rainbow("🔬 Type checking updated files...").bold

    version = Time.now.to_i
    Steep.logger.tagged "watch" do
      Steep.logger.info "Received file system updates: modified=[#{modified.join(",")}], added=[#{added.join(",")}], removed=[#{removed.join(",")}]"

      (modified + added).each do |path|
        p = Pathname(path)
        if watching?(p, files: file_paths, dirs: dir_paths)
          client_writer.write(
            method: "textDocument/didChange",
            params: {
              textDocument: { uri: "file://#{path}", version: version },
              contentChanges: [{ text: p.read }]
            }
          )
        end
      end

      removed.each do |path|
        p = Pathname(path)
        if watching?(p, files: file_paths, dirs: dir_paths)
          client_writer.write(
            method: "textDocument/didChange",
            params: {
              textDocument: { uri: "file://#{path}", version: version },
              contentChanges: [{ text: "" }]
            }
          )
        end
      end
    end

    params = { library_paths: [], inline_paths: [], signature_paths: [], code_paths: [] } #: Server::CustomMethods::TypeCheck::params

    (modified + added).each do |path|
      path = Pathname(path)
      if target = project.target_for_source_path(path)
        params[:code_paths] << [target.name.to_s, path.to_s]
      end
      if target = project.target_for_signature_path(path)
        params[:signature_paths] << [target.name.to_s, path.to_s]
      end
    end

    client_writer.write(Server::CustomMethods::TypeCheck.request(SecureRandom.uuid, params))

    stdout.puts Rainbow("done!").bold
  end.tap(&:start)

  begin
    stdout.puts Rainbow("👀 Watching directories, Ctrl-C to stop.").bold

    params = { library_paths: [], inline_paths: [], signature_paths: [], code_paths: [] } #: Server::CustomMethods::TypeCheck::params
    file_loader = Services::FileLoader.new(base_dir: project.base_dir)
    project.targets.each do |target|
      file_loader.each_path_in_patterns(target.source_pattern, dirs.map(&:to_s)) do |path|
        params[:code_paths] << [target.name.to_s, project.absolute_path(path).to_s]
      end
      file_loader.each_path_in_patterns(target.signature_pattern, dirs.map(&:to_s)) do |path|
        params[:signature_paths] << [target.name.to_s, project.absolute_path(path).to_s]
      end
    end
    client_writer.write(Server::CustomMethods::TypeCheck.request(SecureRandom.uuid, params))

    client_reader.read do |response|
      case response[:method]
      when "textDocument/publishDiagnostics"
        path = PathHelper.to_pathname(response[:params][:uri]) or break
        buffer = RBS::Buffer.new(content: path.read, name: path)
        printer = DiagnosticPrinter.new(stdout: stdout, buffer: buffer)

        diagnostics = response[:params][:diagnostics]
        diagnostics.filter! {|d| keep_diagnostic?(d, severity_level: severity_level) }

        unless diagnostics.empty?
          diagnostics.each do |diagnostic|
            printer.print(diagnostic)
            stdout.flush
          end
        end
      when "window/showMessage"
        # Assuming ERROR message means unrecoverable error.
        message = response[:params]
        if message[:type] == LSP::Constant::MessageType::ERROR
          stdout.puts "Unexpected error reported... 🚨"
        end
      end
    end
  rescue Interrupt
    stdout.puts "Shutting down workers..."
    shutdown_exit(reader: client_reader, writer: client_writer)
  end

  listener.stop
  begin
    main_thread.join
  rescue Interrupt
    master.kill
    begin
      main_thread.join
    rescue
      master.each_worker do |worker|
        worker.kill(force: true)
      end
    end
  end

  0
end

#watching?(changed_path, files:, dirs:) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/steep/drivers/watch.rb', line 24

def watching?(changed_path, files:, dirs:)
  files.empty? || files.include?(changed_path) || dirs.intersect?(changed_path.ascend.to_set)
end