ruby-lsp-proxy 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE.txt +21 -0
- data/README.md +43 -0
- data/exe/ruby-lsp-proxy +8 -0
- data/lib/ruby_lsp_proxy/cli.rb +112 -0
- data/lib/ruby_lsp_proxy/command_runner.rb +36 -0
- data/lib/ruby_lsp_proxy/config.rb +32 -0
- data/lib/ruby_lsp_proxy/container_file_cache.rb +195 -0
- data/lib/ruby_lsp_proxy/detector.rb +198 -0
- data/lib/ruby_lsp_proxy/logger.rb +29 -0
- data/lib/ruby_lsp_proxy/lsp_io.rb +52 -0
- data/lib/ruby_lsp_proxy/message_rewriter.rb +107 -0
- data/lib/ruby_lsp_proxy/path_mapper.rb +159 -0
- data/lib/ruby_lsp_proxy/path_utils.rb +151 -0
- data/lib/ruby_lsp_proxy/proxy_session.rb +101 -0
- data/lib/ruby_lsp_proxy/version.rb +5 -0
- data/lib/ruby_lsp_proxy.rb +17 -0
- metadata +60 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 2d4ea011748471eaf60cf7bad129ee5206f29920b74176b1d8d6c7b890f72346
|
|
4
|
+
data.tar.gz: 29d3338be91c3cb7278f5378183d7acf27c30f41bab11c266000e5c6fa4f04f5
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 6e05257bd2bbfa32d09e69c6496697a16a22dce4a9a8fb0130b61d2b4726df7c948df7d12300dd1f5194c758907996bd6ec1777161245dad2adc0b685ccd29d4
|
|
7
|
+
data.tar.gz: 21874d8c7dd4d177fc0da26e92f91e7bfe48599da40f08231f3c61539ecbf7345023002fbb62e1efcc71913b1dd0ea6840b43b842bde99f9d3aaf4a93de5936d
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yasuhiroki
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# ruby-lsp-proxy
|
|
2
|
+
|
|
3
|
+
A zero-dependency stdio proxy for running `ruby-lsp` inside Docker / Docker Compose containers while keeping editor features (diagnostics, go-to-definition, hover, completion) working transparently on the host.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Auto-detection**: Probes running `docker compose` services, running `docker` containers with a bind mount matching the project root, local `bundle exec ruby-lsp`, and `ruby-lsp` in `PATH`.
|
|
8
|
+
- **Multi-mount URI rewriting**: Rewrites `file://` URIs and `rootPath` across all Docker bind mounts using longest-prefix matching.
|
|
9
|
+
- **On-demand gem & stdlib caching**: When the container `ruby-lsp` returns locations outside host bind mounts (such as `/usr/local/bundle/gems/...` or `/usr/local/lib/ruby/...`), `ruby-lsp-proxy` fetches them in a single batched `docker exec` call into a read-only (`0444`) host cache scoped by container ID. Subsequent jumps or hover requests inside those cached files are reverse-mapped back to their container paths automatically.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
gem build ruby-lsp-proxy.gemspec
|
|
15
|
+
gem install ./ruby-lsp-proxy-*.gem
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
ruby-lsp-proxy [OPTIONS] [PROJECT_DIR]
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
|
|
26
|
+
- `--debug`: Enable debug logging
|
|
27
|
+
- `--detect`, `--dry-run`: Detect target `ruby-lsp` environment and print JSON
|
|
28
|
+
- `-v`, `--version`: Print version and exit
|
|
29
|
+
- `-h`, `--help`: Show help and exit
|
|
30
|
+
|
|
31
|
+
### `vim-lsp` example
|
|
32
|
+
|
|
33
|
+
```vim
|
|
34
|
+
au User lsp_setup call lsp#register_server({
|
|
35
|
+
\ 'name': 'ruby-lsp-proxy',
|
|
36
|
+
\ 'cmd': {server_info->['ruby-lsp-proxy', lsp#utils#find_nearest_parent_file_directory(lsp#utils#get_buffer_path(), 'Gemfile')]},
|
|
37
|
+
\ 'allowlist': ['ruby'],
|
|
38
|
+
\ })
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Environment Variables
|
|
42
|
+
|
|
43
|
+
- `RLP_DEBUG_LOG`: Optional log file path used when `--debug` is enabled (defaults to `$XDG_CACHE_HOME/ruby-lsp-proxy/debug.log` or `~/.cache/ruby-lsp-proxy/debug.log`).
|
data/exe/ruby-lsp-proxy
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "optparse"
|
|
5
|
+
|
|
6
|
+
module RubyLspProxy
|
|
7
|
+
class CLI
|
|
8
|
+
def self.run(argv, env: ENV, stdin: STDIN, stdout: STDOUT, stderr: STDERR)
|
|
9
|
+
options, remaining = parse_options(argv, stdout, stderr)
|
|
10
|
+
return options if options.is_a?(Integer)
|
|
11
|
+
|
|
12
|
+
root = remaining.first || Dir.pwd
|
|
13
|
+
config = Config.new(root, env: env, debug: options[:debug])
|
|
14
|
+
logger = Logger.new(config.debug_log_path)
|
|
15
|
+
runner = CommandRunner.new(env: env)
|
|
16
|
+
target = Detector.new(local_root: config.local_root, runner: runner).detect
|
|
17
|
+
|
|
18
|
+
if target.nil?
|
|
19
|
+
stderr.puts("ruby-lsp-proxy: could not find a runnable ruby-lsp in docker compose, docker, bundle, or PATH (root: #{config.local_root})")
|
|
20
|
+
return 1
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
if options[:detect_only]
|
|
24
|
+
stdout.puts(JSON.pretty_generate(target))
|
|
25
|
+
return 0
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
run_target(target, config, runner, logger, stdin, stdout)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def self.parse_options(argv, stdout, stderr)
|
|
32
|
+
options = { detect_only: false, debug: false }
|
|
33
|
+
show_version = false
|
|
34
|
+
show_help = false
|
|
35
|
+
|
|
36
|
+
parser = OptionParser.new do |opts|
|
|
37
|
+
opts.banner = "Usage: ruby-lsp-proxy [OPTIONS] [PROJECT_DIR]"
|
|
38
|
+
opts.separator ""
|
|
39
|
+
opts.separator "Options:"
|
|
40
|
+
opts.on("--debug", "Enable debug logging (writes to RLP_DEBUG_LOG or <cache_dir>/debug.log)") { options[:debug] = true }
|
|
41
|
+
opts.on("--detect", "--dry-run", "Detect target ruby-lsp environment and print JSON") { options[:detect_only] = true }
|
|
42
|
+
opts.on("-v", "--version", "Print version and exit") { show_version = true }
|
|
43
|
+
opts.on("-h", "--help", "Show this help message and exit") { show_help = true }
|
|
44
|
+
opts.separator ""
|
|
45
|
+
opts.separator "Environment:"
|
|
46
|
+
opts.separator " RLP_DEBUG_LOG Override log file path when --debug is enabled"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
remaining = parser.parse(argv)
|
|
50
|
+
if show_version
|
|
51
|
+
stdout.puts("ruby-lsp-proxy #{RubyLspProxy::VERSION}")
|
|
52
|
+
return 0
|
|
53
|
+
end
|
|
54
|
+
if show_help
|
|
55
|
+
stdout.print(parser.help)
|
|
56
|
+
return 0
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
[options, remaining]
|
|
60
|
+
rescue OptionParser::ParseError => e
|
|
61
|
+
stderr.puts("ruby-lsp-proxy: #{e.message}")
|
|
62
|
+
1
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def self.build_proxy_components(target, config, runner, logger)
|
|
66
|
+
cache = if target[:container_id]
|
|
67
|
+
ContainerFileCache.new(
|
|
68
|
+
container_id: target[:container_id],
|
|
69
|
+
cache_dir: config.cache_dir,
|
|
70
|
+
runner: runner,
|
|
71
|
+
logger: logger
|
|
72
|
+
)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
mapper = PathMapper.new(
|
|
76
|
+
local_root: target[:local_root],
|
|
77
|
+
remote_root: target[:remote_root],
|
|
78
|
+
mounts: target[:mounts],
|
|
79
|
+
cache: cache
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
[cache, mapper]
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def self.run_target(target, config, runner, logger, stdin, stdout)
|
|
86
|
+
cache, mapper = build_proxy_components(target, config, runner, logger)
|
|
87
|
+
|
|
88
|
+
logger.log(
|
|
89
|
+
"Detected mode=#{target[:mode]} cmd=#{target[:cmd].inspect} " \
|
|
90
|
+
"local_root=#{target[:local_root]} remote_root=#{target[:remote_root]} " \
|
|
91
|
+
"mounts=#{mapper.mounts.inspect} cache_root=#{cache&.container_cache_root.inspect}"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
unless mapper.needs_proxy?
|
|
95
|
+
Dir.chdir(target[:local_root])
|
|
96
|
+
Kernel.exec(*target[:cmd])
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
rewriter = MessageRewriter.new(mapper, logger: logger)
|
|
100
|
+
ProxySession.new(
|
|
101
|
+
cmd: target[:cmd],
|
|
102
|
+
local_root: target[:local_root],
|
|
103
|
+
rewriter: rewriter,
|
|
104
|
+
logger: logger,
|
|
105
|
+
input: stdin,
|
|
106
|
+
output: stdout
|
|
107
|
+
).run
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
private_class_method :parse_options, :build_proxy_components, :run_target
|
|
111
|
+
end
|
|
112
|
+
end
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "open3"
|
|
4
|
+
|
|
5
|
+
module RubyLspProxy
|
|
6
|
+
class CommandRunner
|
|
7
|
+
def initialize(env: ENV)
|
|
8
|
+
@env = env
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def command_exists?(name)
|
|
12
|
+
path_env = @env["PATH"].to_s
|
|
13
|
+
return false if path_env.empty?
|
|
14
|
+
|
|
15
|
+
path_env.split(File::PATH_SEPARATOR).any? do |dir|
|
|
16
|
+
next false if dir.empty?
|
|
17
|
+
|
|
18
|
+
candidate = File.join(dir, name)
|
|
19
|
+
File.file?(candidate) && File.executable?(candidate)
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def capture(cmd, chdir: nil)
|
|
24
|
+
opts = chdir ? { chdir: chdir } : {}
|
|
25
|
+
stdout, stderr, status = Open3.capture3(*cmd, **opts)
|
|
26
|
+
[stdout, stderr, status.success?]
|
|
27
|
+
rescue Errno::ENOENT, SystemCallError
|
|
28
|
+
["", "", false]
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def probe(cmd, chdir: nil)
|
|
32
|
+
_stdout, _stderr, ok = capture(cmd, chdir: chdir)
|
|
33
|
+
ok
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RubyLspProxy
|
|
4
|
+
class Config
|
|
5
|
+
def initialize(local_root, env: ENV, debug: false)
|
|
6
|
+
@local_root = PathUtils.normalize_path(local_root)
|
|
7
|
+
@env = env
|
|
8
|
+
@debug = !!debug
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
attr_reader :local_root
|
|
12
|
+
|
|
13
|
+
def debug?
|
|
14
|
+
@debug
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def cache_dir
|
|
18
|
+
xdg_cache = @env["XDG_CACHE_HOME"].to_s.strip
|
|
19
|
+
base = xdg_cache.empty? ? File.expand_path("~/.cache") : xdg_cache
|
|
20
|
+
PathUtils.normalize_path(File.join(base, "ruby-lsp-proxy"))
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def debug_log_path
|
|
24
|
+
return nil unless debug?
|
|
25
|
+
|
|
26
|
+
explicit = @env["RLP_DEBUG_LOG"].to_s.strip
|
|
27
|
+
return PathUtils.normalize_path(explicit) unless explicit.empty?
|
|
28
|
+
|
|
29
|
+
File.join(cache_dir, "debug.log")
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
require "stringio"
|
|
6
|
+
|
|
7
|
+
module RubyLspProxy
|
|
8
|
+
class ContainerFileCache
|
|
9
|
+
MAX_FILE_BYTES = 5 * 1024 * 1024
|
|
10
|
+
MAX_BATCH_FILES = 100
|
|
11
|
+
|
|
12
|
+
FETCH_SCRIPT = format(<<~'RUBY', max_bytes: MAX_FILE_BYTES).freeze
|
|
13
|
+
max = %<max_bytes>d
|
|
14
|
+
STDOUT.binmode
|
|
15
|
+
ARGV.each do |path|
|
|
16
|
+
begin
|
|
17
|
+
next unless File.file?(path) && File.readable?(path)
|
|
18
|
+
next if File.size(path) > max
|
|
19
|
+
|
|
20
|
+
content = File.binread(path)
|
|
21
|
+
path_bytes = path.b
|
|
22
|
+
STDOUT.write("#{path_bytes.bytesize} #{content.bytesize}\n")
|
|
23
|
+
STDOUT.write(path_bytes)
|
|
24
|
+
STDOUT.write(content)
|
|
25
|
+
rescue SystemCallError
|
|
26
|
+
next
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
RUBY
|
|
30
|
+
|
|
31
|
+
def initialize(container_id:, cache_dir:, runner: CommandRunner.new, logger: nil)
|
|
32
|
+
@container_id = container_id.to_s
|
|
33
|
+
@cache_dir = PathUtils.normalize_path(cache_dir)
|
|
34
|
+
@runner = runner
|
|
35
|
+
@logger = logger
|
|
36
|
+
@container_cache_root = PathUtils.normalize_path(File.join(@cache_dir, safe_container_segment(@container_id)))
|
|
37
|
+
@missing_paths = {}
|
|
38
|
+
@mutex = Mutex.new
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
attr_reader :container_id, :container_cache_root
|
|
42
|
+
|
|
43
|
+
def local_path_for(remote_path)
|
|
44
|
+
return nil unless remote_path.is_a?(String) && remote_path.start_with?("/")
|
|
45
|
+
|
|
46
|
+
normalized = File.expand_path(remote_path, "/")
|
|
47
|
+
return nil if normalized == "/" || !normalized.start_with?("/")
|
|
48
|
+
|
|
49
|
+
rel = normalized[1..-1]
|
|
50
|
+
dest = PathUtils.normalize_path(File.join(@container_cache_root, rel))
|
|
51
|
+
return nil unless dest.start_with?("#{@container_cache_root}/")
|
|
52
|
+
|
|
53
|
+
dest
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def remote_path_for(local_path)
|
|
57
|
+
return nil unless local_path.is_a?(String)
|
|
58
|
+
|
|
59
|
+
normalized = PathUtils.normalize_path(local_path)
|
|
60
|
+
prefix = "#{@container_cache_root}/"
|
|
61
|
+
return nil unless normalized.start_with?(prefix)
|
|
62
|
+
|
|
63
|
+
"/#{normalized[prefix.length..-1]}"
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def cached?(remote_path)
|
|
67
|
+
dest = local_path_for(remote_path)
|
|
68
|
+
!dest.nil? && File.file?(dest)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def fetch(remote_path)
|
|
72
|
+
return nil unless remote_path.is_a?(String) && remote_path.start_with?("/")
|
|
73
|
+
|
|
74
|
+
normalized = File.expand_path(remote_path, "/")
|
|
75
|
+
fetch_many([normalized])[normalized]
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def fetch_many(remote_paths)
|
|
79
|
+
return {} if remote_paths.nil? || remote_paths.empty?
|
|
80
|
+
|
|
81
|
+
result, to_fetch = partition_cached_and_pending(remote_paths)
|
|
82
|
+
return result if to_fetch.empty?
|
|
83
|
+
|
|
84
|
+
to_fetch.each_slice(MAX_BATCH_FILES) do |batch|
|
|
85
|
+
fetch_batch(batch, result)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
result
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
private
|
|
92
|
+
|
|
93
|
+
def partition_cached_and_pending(remote_paths)
|
|
94
|
+
result = {}
|
|
95
|
+
to_fetch = []
|
|
96
|
+
seen = {}
|
|
97
|
+
|
|
98
|
+
remote_paths.each do |raw_path|
|
|
99
|
+
next unless raw_path.is_a?(String) && raw_path.start_with?("/")
|
|
100
|
+
|
|
101
|
+
normalized = File.expand_path(raw_path, "/")
|
|
102
|
+
next if seen[normalized]
|
|
103
|
+
|
|
104
|
+
seen[normalized] = true
|
|
105
|
+
dest = local_path_for(normalized)
|
|
106
|
+
next unless dest
|
|
107
|
+
|
|
108
|
+
if File.file?(dest)
|
|
109
|
+
result[normalized] = dest
|
|
110
|
+
elsif !missing?(normalized)
|
|
111
|
+
to_fetch << normalized
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
[result, to_fetch]
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def fetch_batch(batch, result)
|
|
119
|
+
cmd = ["docker", "exec", @container_id, "ruby", "-e", FETCH_SCRIPT, "--", *batch]
|
|
120
|
+
stdout, stderr, ok = @runner.capture(cmd)
|
|
121
|
+
unless ok
|
|
122
|
+
@logger&.log("Cache fetch failed for container #{@container_id}: #{stderr.to_s.strip}")
|
|
123
|
+
return
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
fetched = parse_batch_output(stdout)
|
|
127
|
+
fetched.each do |remote_path, content_bytes|
|
|
128
|
+
dest = local_path_for(remote_path)
|
|
129
|
+
next unless dest
|
|
130
|
+
next if File.directory?(dest)
|
|
131
|
+
|
|
132
|
+
begin
|
|
133
|
+
write_readonly_atomically(dest, content_bytes)
|
|
134
|
+
result[remote_path] = dest
|
|
135
|
+
rescue SystemCallError => e
|
|
136
|
+
@logger&.log("Cache write failed for #{dest}: #{e.message}")
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
@mutex.synchronize do
|
|
141
|
+
batch.each do |path|
|
|
142
|
+
@missing_paths[path] = true unless fetched.key?(path)
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def missing?(path)
|
|
148
|
+
@mutex.synchronize { @missing_paths.key?(path) }
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def safe_container_segment(container_id)
|
|
152
|
+
trimmed = container_id.strip
|
|
153
|
+
return trimmed[0, 12].downcase if trimmed.match?(/\A[0-9a-f]{12,}\z/i)
|
|
154
|
+
|
|
155
|
+
sanitized = trimmed.gsub(/[^A-Za-z0-9._-]/, "_")[0, 64]
|
|
156
|
+
sanitized.nil? || sanitized.empty? ? "default" : sanitized
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def parse_batch_output(stdout)
|
|
160
|
+
io = StringIO.new(stdout.b)
|
|
161
|
+
parsed = {}
|
|
162
|
+
|
|
163
|
+
while (header = io.gets("\n"))
|
|
164
|
+
match = /\A(\d+) (\d+)\z/.match(header.strip)
|
|
165
|
+
break unless match
|
|
166
|
+
|
|
167
|
+
path_len = match[1].to_i
|
|
168
|
+
content_len = match[2].to_i
|
|
169
|
+
path_bytes = io.read(path_len)
|
|
170
|
+
break if path_bytes.nil? || path_bytes.bytesize < path_len
|
|
171
|
+
|
|
172
|
+
content_bytes = io.read(content_len)
|
|
173
|
+
break if content_bytes.nil? || content_bytes.bytesize < content_len
|
|
174
|
+
|
|
175
|
+
path = path_bytes.force_encoding("UTF-8")
|
|
176
|
+
next unless path.valid_encoding?
|
|
177
|
+
|
|
178
|
+
parsed[path] = content_bytes
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
parsed
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def write_readonly_atomically(dest, content_bytes)
|
|
185
|
+
dir = File.dirname(dest)
|
|
186
|
+
FileUtils.mkdir_p(dir)
|
|
187
|
+
staging_path = File.join(dir, ".tmp.#{Process.pid}.#{SecureRandom.hex(6)}")
|
|
188
|
+
File.binwrite(staging_path, content_bytes)
|
|
189
|
+
File.chmod(0o444, staging_path)
|
|
190
|
+
File.rename(staging_path, dest)
|
|
191
|
+
ensure
|
|
192
|
+
FileUtils.rm_f(staging_path) if staging_path
|
|
193
|
+
end
|
|
194
|
+
end
|
|
195
|
+
end
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module RubyLspProxy
|
|
6
|
+
class Detector
|
|
7
|
+
COMPOSE_FILENAMES = %w[compose.yaml compose.yml docker-compose.yaml docker-compose.yml].freeze
|
|
8
|
+
PREFERRED_COMPOSE_SERVICES = %w[app web rails ruby backend api].freeze
|
|
9
|
+
|
|
10
|
+
def initialize(local_root:, runner: CommandRunner.new)
|
|
11
|
+
@local_root = PathUtils.normalize_path(local_root)
|
|
12
|
+
@runner = runner
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def detect
|
|
16
|
+
detect_compose || detect_docker || detect_local
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
private
|
|
20
|
+
|
|
21
|
+
def detect_compose
|
|
22
|
+
candidates = collect_compose_candidates
|
|
23
|
+
return nil if candidates.empty?
|
|
24
|
+
|
|
25
|
+
[
|
|
26
|
+
["docker-compose-bundle", %w[bundle exec ruby-lsp]],
|
|
27
|
+
["docker-compose", %w[ruby-lsp]]
|
|
28
|
+
].each do |mode, lsp_cmd|
|
|
29
|
+
candidates.each do |candidate|
|
|
30
|
+
cmd = [*candidate[:base_cmd], "exec", "-T", "-w", candidate[:remote_root], candidate[:service], *lsp_cmd]
|
|
31
|
+
next unless @runner.probe([*cmd, "--version"], chdir: @local_root)
|
|
32
|
+
|
|
33
|
+
return build_target(
|
|
34
|
+
mode: mode,
|
|
35
|
+
cmd: cmd,
|
|
36
|
+
remote_root: candidate[:remote_root],
|
|
37
|
+
container_id: candidate[:container_id],
|
|
38
|
+
mounts: candidate[:mounts]
|
|
39
|
+
)
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
nil
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def detect_docker
|
|
47
|
+
candidates = collect_docker_candidates
|
|
48
|
+
return nil if candidates.empty?
|
|
49
|
+
|
|
50
|
+
[
|
|
51
|
+
["docker-exec-bundle", %w[bundle exec ruby-lsp]],
|
|
52
|
+
["docker-exec", %w[ruby-lsp]]
|
|
53
|
+
].each do |mode, lsp_cmd|
|
|
54
|
+
candidates.each do |candidate|
|
|
55
|
+
probe_cmd = ["docker", "exec", "-w", candidate[:remote_root], candidate[:container], *lsp_cmd, "--version"]
|
|
56
|
+
next unless @runner.probe(probe_cmd)
|
|
57
|
+
|
|
58
|
+
cmd = ["docker", "exec", "-i", "-w", candidate[:remote_root], candidate[:container], *lsp_cmd]
|
|
59
|
+
return build_target(
|
|
60
|
+
mode: mode,
|
|
61
|
+
cmd: cmd,
|
|
62
|
+
remote_root: candidate[:remote_root],
|
|
63
|
+
container_id: candidate[:container_id],
|
|
64
|
+
mounts: candidate[:mounts]
|
|
65
|
+
)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
nil
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def detect_local
|
|
73
|
+
if @runner.command_exists?("bundle") && File.file?(File.join(@local_root, "Gemfile"))
|
|
74
|
+
cmd = %w[bundle exec ruby-lsp]
|
|
75
|
+
return build_target(mode: "local-bundle", cmd: cmd, remote_root: @local_root) if @runner.probe([*cmd, "--version"], chdir: @local_root)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
if @runner.command_exists?("ruby-lsp")
|
|
79
|
+
cmd = %w[ruby-lsp]
|
|
80
|
+
return build_target(mode: "local", cmd: cmd, remote_root: @local_root) if @runner.probe([*cmd, "--version"], chdir: @local_root)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
nil
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def build_target(mode:, cmd:, remote_root:, container_id: nil, mounts: nil)
|
|
87
|
+
{
|
|
88
|
+
mode: mode,
|
|
89
|
+
cmd: cmd,
|
|
90
|
+
local_root: @local_root,
|
|
91
|
+
remote_root: remote_root,
|
|
92
|
+
container_id: container_id,
|
|
93
|
+
mounts: mounts || [{ local: @local_root, remote: remote_root }]
|
|
94
|
+
}
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def compose_file_present?
|
|
98
|
+
COMPOSE_FILENAMES.any? { |name| File.file?(File.join(@local_root, name)) }
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def inspect_containers(ids_or_names)
|
|
102
|
+
return [] if ids_or_names.empty?
|
|
103
|
+
|
|
104
|
+
stdout, _stderr, ok = @runner.capture(["docker", "inspect", *ids_or_names])
|
|
105
|
+
return [] unless ok
|
|
106
|
+
|
|
107
|
+
parsed = JSON.parse(stdout)
|
|
108
|
+
parsed.is_a?(Array) ? parsed : []
|
|
109
|
+
rescue JSON::ParserError
|
|
110
|
+
[]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def resolve_container_remote_root(container_inspect)
|
|
114
|
+
from_mount = PathUtils.resolve_remote_from_mounts(container_inspect["Mounts"], @local_root)
|
|
115
|
+
return from_mount if from_mount
|
|
116
|
+
|
|
117
|
+
workdir = container_inspect.dig("Config", "WorkingDir").to_s
|
|
118
|
+
return PathUtils.normalize_path(workdir) unless workdir.empty?
|
|
119
|
+
|
|
120
|
+
@local_root
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def build_candidate_mounts(container_inspect, remote_root)
|
|
124
|
+
mounts = PathUtils.extract_bind_mounts(container_inspect["Mounts"])
|
|
125
|
+
return mounts if mounts.any? { |m| m[:local] == @local_root }
|
|
126
|
+
|
|
127
|
+
[{ local: @local_root, remote: remote_root }] + mounts
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def collect_compose_candidates
|
|
131
|
+
return [] unless @runner.command_exists?("docker")
|
|
132
|
+
return [] unless compose_file_present?
|
|
133
|
+
|
|
134
|
+
base_cmd = %w[docker compose]
|
|
135
|
+
stdout, _stderr, ok = @runner.capture([*base_cmd, "ps", "--status", "running", "--services"], chdir: @local_root)
|
|
136
|
+
return [] unless ok
|
|
137
|
+
|
|
138
|
+
running_services = stdout.lines.map(&:strip).reject(&:empty?)
|
|
139
|
+
return [] if running_services.empty?
|
|
140
|
+
|
|
141
|
+
prioritized = PREFERRED_COMPOSE_SERVICES.select { |s| running_services.include?(s) }
|
|
142
|
+
services = prioritized + (running_services - prioritized)
|
|
143
|
+
|
|
144
|
+
candidates = []
|
|
145
|
+
services.each do |service|
|
|
146
|
+
cid_out, _err, cid_ok = @runner.capture([*base_cmd, "ps", "-q", service], chdir: @local_root)
|
|
147
|
+
next unless cid_ok
|
|
148
|
+
|
|
149
|
+
cid = cid_out.lines.map(&:strip).reject(&:empty?).first
|
|
150
|
+
next unless cid
|
|
151
|
+
|
|
152
|
+
container_inspect = inspect_containers([cid]).first
|
|
153
|
+
next unless container_inspect
|
|
154
|
+
|
|
155
|
+
remote_root = resolve_container_remote_root(container_inspect)
|
|
156
|
+
candidates << {
|
|
157
|
+
base_cmd: base_cmd,
|
|
158
|
+
service: service,
|
|
159
|
+
remote_root: remote_root,
|
|
160
|
+
container_id: container_inspect["Id"].to_s.empty? ? cid : container_inspect["Id"].to_s,
|
|
161
|
+
mounts: build_candidate_mounts(container_inspect, remote_root)
|
|
162
|
+
}
|
|
163
|
+
end
|
|
164
|
+
candidates
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def collect_docker_candidates
|
|
168
|
+
return [] unless @runner.command_exists?("docker")
|
|
169
|
+
|
|
170
|
+
ps_out, _err, ps_ok = @runner.capture(%w[docker ps -q])
|
|
171
|
+
return [] unless ps_ok
|
|
172
|
+
|
|
173
|
+
ids = ps_out.lines.map(&:strip).reject(&:empty?)
|
|
174
|
+
return [] if ids.empty?
|
|
175
|
+
|
|
176
|
+
candidates = []
|
|
177
|
+
inspect_containers(ids).each do |container_inspect|
|
|
178
|
+
bind_mounts = PathUtils.extract_bind_mounts(container_inspect["Mounts"])
|
|
179
|
+
exact_mount = bind_mounts.find { |m| m[:local] == @local_root }
|
|
180
|
+
next unless exact_mount
|
|
181
|
+
|
|
182
|
+
name = container_inspect["Name"].to_s.sub(%r{\A/}, "")
|
|
183
|
+
next if name.empty?
|
|
184
|
+
|
|
185
|
+
container_id = container_inspect["Id"].to_s.empty? ? name : container_inspect["Id"].to_s
|
|
186
|
+
|
|
187
|
+
candidates << {
|
|
188
|
+
container: name,
|
|
189
|
+
remote_root: exact_mount[:remote],
|
|
190
|
+
container_id: container_id,
|
|
191
|
+
mounts: bind_mounts
|
|
192
|
+
}
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
candidates
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
|
|
5
|
+
module RubyLspProxy
|
|
6
|
+
class Logger
|
|
7
|
+
def initialize(path)
|
|
8
|
+
@path = path.nil? || path.empty? ? nil : path
|
|
9
|
+
@mutex = Mutex.new
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def enabled?
|
|
13
|
+
!@path.nil?
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def log(message)
|
|
17
|
+
return unless @path
|
|
18
|
+
|
|
19
|
+
@mutex.synchronize do
|
|
20
|
+
FileUtils.mkdir_p(File.dirname(@path))
|
|
21
|
+
File.open(@path, "a", encoding: "UTF-8") do |fh|
|
|
22
|
+
fh.puts(message.to_s.chomp)
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
rescue SystemCallError
|
|
26
|
+
nil
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RubyLspProxy
|
|
4
|
+
module LspIO
|
|
5
|
+
module_function
|
|
6
|
+
|
|
7
|
+
def read_exact(io, length)
|
|
8
|
+
buf = +"".b
|
|
9
|
+
while buf.bytesize < length
|
|
10
|
+
chunk = io.read(length - buf.bytesize)
|
|
11
|
+
return nil if chunk.nil? || chunk.empty?
|
|
12
|
+
|
|
13
|
+
buf << chunk
|
|
14
|
+
end
|
|
15
|
+
buf
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def read_message(io)
|
|
19
|
+
headers = []
|
|
20
|
+
while (line = io.gets("\n"))
|
|
21
|
+
break if line == "\r\n" || line == "\n"
|
|
22
|
+
|
|
23
|
+
headers << line
|
|
24
|
+
end
|
|
25
|
+
return nil if headers.empty? && line.nil?
|
|
26
|
+
|
|
27
|
+
content_length = nil
|
|
28
|
+
headers.each do |raw_header|
|
|
29
|
+
header = raw_header.encode("ASCII", invalid: :replace, undef: :replace).strip
|
|
30
|
+
next unless header.include?(":")
|
|
31
|
+
|
|
32
|
+
name, value = header.split(":", 2)
|
|
33
|
+
if name.strip.casecmp("content-length").zero?
|
|
34
|
+
content_length = Integer(value.strip, 10)
|
|
35
|
+
break
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
return nil if content_length.nil? || content_length < 0
|
|
39
|
+
|
|
40
|
+
read_exact(io, content_length)
|
|
41
|
+
rescue ArgumentError
|
|
42
|
+
nil
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def write_message(io, body_bytes)
|
|
46
|
+
body = body_bytes.b
|
|
47
|
+
header = "Content-Length: #{body.bytesize}\r\n\r\n".b
|
|
48
|
+
io.write(header + body)
|
|
49
|
+
io.flush
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module RubyLspProxy
|
|
6
|
+
class MessageRewriter
|
|
7
|
+
# NOTE: Exclude free-form text, markdown, and log fields from both URI rewriting and cache prefetching.
|
|
8
|
+
SKIP_VALUE_KEYS = %w[
|
|
9
|
+
text
|
|
10
|
+
newText
|
|
11
|
+
insertText
|
|
12
|
+
filterText
|
|
13
|
+
sortText
|
|
14
|
+
label
|
|
15
|
+
detail
|
|
16
|
+
documentation
|
|
17
|
+
message
|
|
18
|
+
value
|
|
19
|
+
].freeze
|
|
20
|
+
|
|
21
|
+
def initialize(mapper, logger: nil)
|
|
22
|
+
@mapper = mapper
|
|
23
|
+
@logger = logger
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def rewrite_client_to_server(body_bytes)
|
|
27
|
+
payload = JSON.parse(body_bytes.dup.force_encoding("UTF-8"))
|
|
28
|
+
rewritten = rewrite_node(payload, :c2s)
|
|
29
|
+
JSON.generate(rewritten).b
|
|
30
|
+
rescue JSON::ParserError, Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError => e
|
|
31
|
+
@logger&.log("Skipped C->S message rewrite (#{e.class}): #{e.message}")
|
|
32
|
+
body_bytes
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def rewrite_server_to_client(body_bytes)
|
|
36
|
+
payload = JSON.parse(body_bytes.dup.force_encoding("UTF-8"))
|
|
37
|
+
if @mapper.cache_enabled?
|
|
38
|
+
remote_paths = collect_remote_paths(payload)
|
|
39
|
+
@mapper.prefetch_remote_paths(remote_paths) unless remote_paths.empty?
|
|
40
|
+
end
|
|
41
|
+
rewritten = rewrite_node(payload, :s2c)
|
|
42
|
+
JSON.generate(rewritten).b
|
|
43
|
+
rescue JSON::ParserError, Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError => e
|
|
44
|
+
@logger&.log("Skipped S->C message rewrite (#{e.class}): #{e.message}")
|
|
45
|
+
body_bytes
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
def rewrite_uri(uri, direction)
|
|
51
|
+
direction == :c2s ? @mapper.local_to_remote_uri(uri) : @mapper.remote_to_local_uri(uri)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def rewrite_path(path, direction)
|
|
55
|
+
direction == :c2s ? @mapper.local_to_remote_path(path) : @mapper.remote_to_local_path(path)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def rewrite_node(node, direction)
|
|
59
|
+
case node
|
|
60
|
+
when Hash
|
|
61
|
+
rewritten = {}
|
|
62
|
+
node.each do |key, value|
|
|
63
|
+
key_str = key.to_s
|
|
64
|
+
new_key = key_str.start_with?("file://") ? rewrite_uri(key_str, direction) : key
|
|
65
|
+
rewritten[new_key] = if SKIP_VALUE_KEYS.include?(key_str)
|
|
66
|
+
value
|
|
67
|
+
elsif key_str == "rootPath" && value.is_a?(String)
|
|
68
|
+
rewrite_path(value, direction)
|
|
69
|
+
else
|
|
70
|
+
rewrite_node(value, direction)
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
rewritten
|
|
74
|
+
when Array
|
|
75
|
+
node.map { |item| rewrite_node(item, direction) }
|
|
76
|
+
when String
|
|
77
|
+
node.start_with?("file://") ? rewrite_uri(node, direction) : node
|
|
78
|
+
else
|
|
79
|
+
node
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def collect_remote_paths(node, paths = [])
|
|
84
|
+
case node
|
|
85
|
+
when Hash
|
|
86
|
+
node.each do |key, value|
|
|
87
|
+
key_str = key.to_s
|
|
88
|
+
if key_str.start_with?("file://")
|
|
89
|
+
remote = @mapper.uncached_remote_path(key_str)
|
|
90
|
+
paths << remote if remote
|
|
91
|
+
end
|
|
92
|
+
next if SKIP_VALUE_KEYS.include?(key_str)
|
|
93
|
+
|
|
94
|
+
collect_remote_paths(value, paths)
|
|
95
|
+
end
|
|
96
|
+
when Array
|
|
97
|
+
node.each { |item| collect_remote_paths(item, paths) }
|
|
98
|
+
when String
|
|
99
|
+
if node.start_with?("file://")
|
|
100
|
+
remote = @mapper.uncached_remote_path(node)
|
|
101
|
+
paths << remote if remote
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
paths
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RubyLspProxy
|
|
4
|
+
class PathMapper
|
|
5
|
+
def initialize(local_root:, remote_root:, mounts: [], cache: nil)
|
|
6
|
+
@local_root = PathUtils.normalize_path(local_root)
|
|
7
|
+
@remote_root = PathUtils.normalize_path(remote_root)
|
|
8
|
+
@cache = cache
|
|
9
|
+
|
|
10
|
+
mount_entries = build_mount_entries(mounts)
|
|
11
|
+
@mounts = mount_entries.map { |m| { local: m[:local], remote: m[:remote] } }
|
|
12
|
+
@local_to_remote_mounts = mount_entries.sort_by { |m| [-m[:local].length, m[:local] == @local_root ? 0 : 1] }
|
|
13
|
+
@remote_to_local_mounts = mount_entries.sort_by { |m| [-m[:remote].length, m[:remote] == @remote_root ? 0 : 1] }
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
attr_reader :local_root, :remote_root, :mounts
|
|
17
|
+
|
|
18
|
+
def cache_enabled?
|
|
19
|
+
!@cache.nil?
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def needs_proxy?
|
|
23
|
+
cache_enabled? || @mounts.any? { |m| m[:local] != m[:remote] }
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def local_to_remote_path(path)
|
|
27
|
+
return path unless path.is_a?(String)
|
|
28
|
+
|
|
29
|
+
if @cache
|
|
30
|
+
remote = @cache.remote_path_for(path)
|
|
31
|
+
return remote if remote
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
@local_to_remote_mounts.each do |mount|
|
|
35
|
+
if PathUtils.match_prefix?(path, mount[:local])
|
|
36
|
+
return PathUtils.replace_prefix(path, mount[:local], mount[:remote])
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
path
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def local_to_remote_uri(uri)
|
|
44
|
+
return uri unless uri.is_a?(String) && uri.start_with?("file://")
|
|
45
|
+
|
|
46
|
+
base, suffix = PathUtils.split_uri_suffix(uri)
|
|
47
|
+
|
|
48
|
+
if @cache
|
|
49
|
+
decoded = PathUtils.decode_uri_path(base)
|
|
50
|
+
if decoded
|
|
51
|
+
remote = @cache.remote_path_for(decoded)
|
|
52
|
+
return "#{PathUtils.path_to_uri(remote)}#{suffix}" if remote
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
@local_to_remote_mounts.each do |mount|
|
|
57
|
+
mount[:local_uri_prefixes].each do |from_uri|
|
|
58
|
+
next unless PathUtils.match_prefix?(base, from_uri)
|
|
59
|
+
|
|
60
|
+
replaced = PathUtils.replace_prefix(base, from_uri, mount[:remote_uri])
|
|
61
|
+
return "#{replaced}#{suffix}"
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
uri
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def remote_to_local_path(path)
|
|
69
|
+
return path unless path.is_a?(String)
|
|
70
|
+
|
|
71
|
+
@remote_to_local_mounts.each do |mount|
|
|
72
|
+
if PathUtils.match_prefix?(path, mount[:remote])
|
|
73
|
+
return PathUtils.replace_prefix(path, mount[:remote], mount[:local])
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
if @cache
|
|
78
|
+
cached = @cache.local_path_for(path)
|
|
79
|
+
return cached if cached && File.file?(cached)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
path
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def remote_to_local_uri(uri)
|
|
86
|
+
return uri unless uri.is_a?(String) && uri.start_with?("file://")
|
|
87
|
+
|
|
88
|
+
base, suffix = PathUtils.split_uri_suffix(uri)
|
|
89
|
+
|
|
90
|
+
@remote_to_local_mounts.each do |mount|
|
|
91
|
+
mount[:remote_uri_prefixes].each do |from_uri|
|
|
92
|
+
next unless PathUtils.match_prefix?(base, from_uri)
|
|
93
|
+
|
|
94
|
+
replaced = PathUtils.replace_prefix(base, from_uri, mount[:local_uri])
|
|
95
|
+
return "#{replaced}#{suffix}"
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
if @cache
|
|
100
|
+
remote_path = PathUtils.decode_uri_path(base)
|
|
101
|
+
if remote_path
|
|
102
|
+
cached = @cache.fetch(remote_path)
|
|
103
|
+
return "#{PathUtils.path_to_uri(cached)}#{suffix}" if cached
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
uri
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def uncached_remote_path(uri)
|
|
111
|
+
return nil unless cache_enabled? && uri.is_a?(String) && uri.start_with?("file://")
|
|
112
|
+
|
|
113
|
+
base, = PathUtils.split_uri_suffix(uri)
|
|
114
|
+
mapped = @remote_to_local_mounts.any? do |mount|
|
|
115
|
+
mount[:remote_uri_prefixes].any? { |from_uri| PathUtils.match_prefix?(base, from_uri) }
|
|
116
|
+
end
|
|
117
|
+
return nil if mapped
|
|
118
|
+
|
|
119
|
+
PathUtils.decode_uri_path(base)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def prefetch_remote_paths(paths)
|
|
123
|
+
return {} unless @cache && !paths.empty?
|
|
124
|
+
|
|
125
|
+
@cache.fetch_many(paths)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
private
|
|
129
|
+
|
|
130
|
+
def build_mount_entries(raw_mounts)
|
|
131
|
+
seen_local = {}
|
|
132
|
+
entries = []
|
|
133
|
+
|
|
134
|
+
add_entry = lambda do |local, remote|
|
|
135
|
+
return if seen_local[local]
|
|
136
|
+
|
|
137
|
+
seen_local[local] = true
|
|
138
|
+
entries << {
|
|
139
|
+
local: local,
|
|
140
|
+
remote: remote,
|
|
141
|
+
local_uri: PathUtils.path_to_uri(local),
|
|
142
|
+
local_uri_prefixes: PathUtils.make_uri_prefixes(local),
|
|
143
|
+
remote_uri: PathUtils.path_to_uri(remote),
|
|
144
|
+
remote_uri_prefixes: PathUtils.make_uri_prefixes(remote)
|
|
145
|
+
}
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
add_entry.call(@local_root, @remote_root)
|
|
149
|
+
|
|
150
|
+
Array(raw_mounts).each do |mount|
|
|
151
|
+
local = PathUtils.normalize_path(mount[:local] || mount["local"])
|
|
152
|
+
remote = PathUtils.normalize_path(mount[:remote] || mount["remote"])
|
|
153
|
+
add_entry.call(local, remote)
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
entries
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RubyLspProxy
|
|
4
|
+
module PathUtils
|
|
5
|
+
URI_SAFE_PATTERN = %r{\A[A-Za-z0-9/:@!$&'()*+,;=.\-_~]\z}.freeze
|
|
6
|
+
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def normalize_path(path)
|
|
10
|
+
expanded = File.expand_path(path)
|
|
11
|
+
stripped = expanded.sub(%r{/+\z}, "")
|
|
12
|
+
stripped.empty? ? "/" : stripped
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def normalize_host_mount_source(raw_source)
|
|
16
|
+
# NOTE: Docker Desktop on macOS may expose bind mount sources under /host_mnt.
|
|
17
|
+
cleaned = raw_source.to_s.sub(%r{\A/host_mnt(?=/|$)}, "")
|
|
18
|
+
cleaned = "/" if cleaned.empty?
|
|
19
|
+
normalize_path(cleaned)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def encode_uri_path(path)
|
|
23
|
+
return "/" if path == "/"
|
|
24
|
+
|
|
25
|
+
encoded = +""
|
|
26
|
+
path.encode("UTF-8").each_byte do |byte|
|
|
27
|
+
ch = byte.chr(Encoding::ASCII_8BIT)
|
|
28
|
+
encoded << (ch.match?(URI_SAFE_PATTERN) ? ch : format("%%%02X", byte))
|
|
29
|
+
end
|
|
30
|
+
encoded
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def path_to_uri(path)
|
|
34
|
+
normalized = normalize_path(path)
|
|
35
|
+
return "file:///" if normalized == "/"
|
|
36
|
+
|
|
37
|
+
"file://#{encode_uri_path(normalized)}"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def split_uri_suffix(uri)
|
|
41
|
+
idx = uri.index(/[?#]/)
|
|
42
|
+
return [uri, ""] if idx.nil?
|
|
43
|
+
|
|
44
|
+
[uri[0...idx], uri[idx..-1]]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def decode_uri_path(uri)
|
|
48
|
+
return nil unless uri.is_a?(String) && uri.start_with?("file://")
|
|
49
|
+
|
|
50
|
+
base, = split_uri_suffix(uri)
|
|
51
|
+
raw_path = if base.start_with?("file://localhost/")
|
|
52
|
+
base.delete_prefix("file://localhost")
|
|
53
|
+
elsif base.start_with?("file:///")
|
|
54
|
+
base.delete_prefix("file://")
|
|
55
|
+
else
|
|
56
|
+
return nil
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
decoded = raw_path.b.gsub(/%([0-9A-Fa-f]{2})/) { [Regexp.last_match(1)].pack("H2") }.force_encoding("UTF-8")
|
|
60
|
+
return nil unless decoded.valid_encoding?
|
|
61
|
+
|
|
62
|
+
normalize_path(decoded)
|
|
63
|
+
rescue Encoding::CompatibilityError
|
|
64
|
+
nil
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def make_uri_prefixes(path)
|
|
68
|
+
normalized = normalize_path(path)
|
|
69
|
+
return ["file:///"] if normalized == "/"
|
|
70
|
+
|
|
71
|
+
quoted = "file://#{encode_uri_path(normalized)}"
|
|
72
|
+
raw = "file://#{normalized}"
|
|
73
|
+
quoted == raw ? [quoted] : [quoted, raw]
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def match_prefix?(value, prefix)
|
|
77
|
+
return true if value == prefix
|
|
78
|
+
return false unless value.start_with?(prefix)
|
|
79
|
+
|
|
80
|
+
prefix.end_with?("/") || (value.length > prefix.length && %w[/ ? #].include?(value[prefix.length]))
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def replace_prefix(value, old, new)
|
|
84
|
+
return new if value == old
|
|
85
|
+
return value unless value.start_with?(old)
|
|
86
|
+
|
|
87
|
+
rest = value[old.length..-1]
|
|
88
|
+
if old.end_with?("/")
|
|
89
|
+
return new.end_with?("/") ? "#{new}#{rest}" : "#{new}/#{rest}"
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
return value unless value.length > old.length && %w[/ ? #].include?(value[old.length])
|
|
93
|
+
|
|
94
|
+
if rest.start_with?("/") && new.end_with?("/")
|
|
95
|
+
"#{new}#{rest[1..-1]}"
|
|
96
|
+
else
|
|
97
|
+
"#{new}#{rest}"
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def extract_bind_mounts(mounts)
|
|
102
|
+
return [] unless mounts.is_a?(Array)
|
|
103
|
+
|
|
104
|
+
seen = {}
|
|
105
|
+
result = []
|
|
106
|
+
mounts.each do |mount|
|
|
107
|
+
next unless mount.is_a?(Hash) && mount["Type"] == "bind"
|
|
108
|
+
|
|
109
|
+
raw_source = mount["Source"].to_s
|
|
110
|
+
raw_dest = mount["Destination"].to_s
|
|
111
|
+
next if raw_source.empty? || raw_dest.empty?
|
|
112
|
+
|
|
113
|
+
local = normalize_host_mount_source(raw_source)
|
|
114
|
+
remote = normalize_path(raw_dest)
|
|
115
|
+
key = [local, remote]
|
|
116
|
+
next if seen[key]
|
|
117
|
+
|
|
118
|
+
seen[key] = true
|
|
119
|
+
result << { local: local, remote: remote }
|
|
120
|
+
end
|
|
121
|
+
result
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def resolve_remote_from_mounts(mounts, local_root)
|
|
125
|
+
bind_mounts = extract_bind_mounts(mounts)
|
|
126
|
+
return nil if bind_mounts.empty?
|
|
127
|
+
|
|
128
|
+
normalized_root = normalize_path(local_root)
|
|
129
|
+
best_prefix_len = -1
|
|
130
|
+
best_prefix_remote = nil
|
|
131
|
+
|
|
132
|
+
bind_mounts.each do |mount|
|
|
133
|
+
source = mount[:local]
|
|
134
|
+
dest = mount[:remote]
|
|
135
|
+
return dest if normalized_root == source
|
|
136
|
+
|
|
137
|
+
if source == "/"
|
|
138
|
+
next if best_prefix_len >= 1
|
|
139
|
+
|
|
140
|
+
best_prefix_len = 1
|
|
141
|
+
best_prefix_remote = replace_prefix(normalized_root, "/", dest)
|
|
142
|
+
elsif normalized_root.start_with?("#{source}/") && source.length > best_prefix_len
|
|
143
|
+
best_prefix_len = source.length
|
|
144
|
+
best_prefix_remote = replace_prefix(normalized_root, source, dest)
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
best_prefix_remote
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "open3"
|
|
4
|
+
|
|
5
|
+
module RubyLspProxy
|
|
6
|
+
class ProxySession
|
|
7
|
+
def initialize(cmd:, local_root:, rewriter:, logger: nil, input: STDIN, output: STDOUT)
|
|
8
|
+
@cmd = cmd
|
|
9
|
+
@local_root = local_root
|
|
10
|
+
@rewriter = rewriter
|
|
11
|
+
@logger = logger
|
|
12
|
+
@input = input
|
|
13
|
+
@output = output
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def run
|
|
17
|
+
@input.binmode
|
|
18
|
+
@output.binmode
|
|
19
|
+
@output.sync = true
|
|
20
|
+
|
|
21
|
+
child_in, child_out, wait_thr = Open3.popen2(*@cmd, chdir: @local_root)
|
|
22
|
+
child_in.binmode
|
|
23
|
+
child_in.sync = true
|
|
24
|
+
child_out.binmode
|
|
25
|
+
|
|
26
|
+
previous_traps = install_signal_traps(wait_thr.pid)
|
|
27
|
+
|
|
28
|
+
t_in = Thread.new do
|
|
29
|
+
forward_stream(from: @input, to: child_in, label: "C->S", close_on_exit: child_in) do |body|
|
|
30
|
+
@rewriter.rewrite_client_to_server(body)
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
t_out = Thread.new do
|
|
35
|
+
forward_stream(from: child_out, to: @output, label: "S->C", close_on_exit: child_out) do |body|
|
|
36
|
+
@rewriter.rewrite_server_to_client(body)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
t_out.join
|
|
41
|
+
close_stream_safely(child_in)
|
|
42
|
+
close_stream_safely(child_out)
|
|
43
|
+
unless t_in.join(0.1)
|
|
44
|
+
t_in.kill
|
|
45
|
+
t_in.join(0.1)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
status = wait_thr.value
|
|
49
|
+
status.exitstatus || 0
|
|
50
|
+
ensure
|
|
51
|
+
close_stream_safely(child_in)
|
|
52
|
+
close_stream_safely(child_out)
|
|
53
|
+
restore_signal_traps(previous_traps) if previous_traps
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
def install_signal_traps(child_pid)
|
|
59
|
+
previous = {}
|
|
60
|
+
%w[TERM INT].each do |sig|
|
|
61
|
+
previous[sig] = Signal.trap(sig) do
|
|
62
|
+
# CRITICAL: Never call @logger or acquire any Mutex inside Signal.trap (raises ThreadError).
|
|
63
|
+
Process.kill("TERM", child_pid)
|
|
64
|
+
rescue Errno::ESRCH
|
|
65
|
+
nil
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
previous
|
|
69
|
+
rescue ArgumentError
|
|
70
|
+
nil
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def restore_signal_traps(previous)
|
|
74
|
+
previous.each do |sig, handler|
|
|
75
|
+
Signal.trap(sig, handler || "DEFAULT")
|
|
76
|
+
end
|
|
77
|
+
rescue ArgumentError
|
|
78
|
+
nil
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def forward_stream(from:, to:, label:, close_on_exit:)
|
|
82
|
+
while (body = LspIO.read_message(from))
|
|
83
|
+
rewritten = yield(body)
|
|
84
|
+
@logger&.log("#{label}: #{rewritten.dup.force_encoding('UTF-8')[0, 300]}")
|
|
85
|
+
LspIO.write_message(to, rewritten)
|
|
86
|
+
end
|
|
87
|
+
rescue IOError, SystemCallError
|
|
88
|
+
nil
|
|
89
|
+
ensure
|
|
90
|
+
close_stream_safely(close_on_exit)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def close_stream_safely(stream)
|
|
94
|
+
return if stream.nil? || stream.closed?
|
|
95
|
+
|
|
96
|
+
stream.close
|
|
97
|
+
rescue IOError, SystemCallError
|
|
98
|
+
nil
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "ruby_lsp_proxy/version"
|
|
4
|
+
require_relative "ruby_lsp_proxy/path_utils"
|
|
5
|
+
require_relative "ruby_lsp_proxy/config"
|
|
6
|
+
require_relative "ruby_lsp_proxy/logger"
|
|
7
|
+
require_relative "ruby_lsp_proxy/command_runner"
|
|
8
|
+
require_relative "ruby_lsp_proxy/lsp_io"
|
|
9
|
+
require_relative "ruby_lsp_proxy/container_file_cache"
|
|
10
|
+
require_relative "ruby_lsp_proxy/path_mapper"
|
|
11
|
+
require_relative "ruby_lsp_proxy/message_rewriter"
|
|
12
|
+
require_relative "ruby_lsp_proxy/detector"
|
|
13
|
+
require_relative "ruby_lsp_proxy/proxy_session"
|
|
14
|
+
require_relative "ruby_lsp_proxy/cli"
|
|
15
|
+
|
|
16
|
+
module RubyLspProxy
|
|
17
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: ruby-lsp-proxy
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- yasuhiroki
|
|
8
|
+
bindir: exe
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: Auto-detects ruby-lsp in Docker Compose, Docker, or local environments,
|
|
13
|
+
rewrites multi-mount file URIs bidirectionally, and caches container gem/stdlib
|
|
14
|
+
files on demand for editor navigation.
|
|
15
|
+
email:
|
|
16
|
+
- yasuhiroki.duck@gmail.com
|
|
17
|
+
executables:
|
|
18
|
+
- ruby-lsp-proxy
|
|
19
|
+
extensions: []
|
|
20
|
+
extra_rdoc_files: []
|
|
21
|
+
files:
|
|
22
|
+
- LICENSE.txt
|
|
23
|
+
- README.md
|
|
24
|
+
- exe/ruby-lsp-proxy
|
|
25
|
+
- lib/ruby_lsp_proxy.rb
|
|
26
|
+
- lib/ruby_lsp_proxy/cli.rb
|
|
27
|
+
- lib/ruby_lsp_proxy/command_runner.rb
|
|
28
|
+
- lib/ruby_lsp_proxy/config.rb
|
|
29
|
+
- lib/ruby_lsp_proxy/container_file_cache.rb
|
|
30
|
+
- lib/ruby_lsp_proxy/detector.rb
|
|
31
|
+
- lib/ruby_lsp_proxy/logger.rb
|
|
32
|
+
- lib/ruby_lsp_proxy/lsp_io.rb
|
|
33
|
+
- lib/ruby_lsp_proxy/message_rewriter.rb
|
|
34
|
+
- lib/ruby_lsp_proxy/path_mapper.rb
|
|
35
|
+
- lib/ruby_lsp_proxy/path_utils.rb
|
|
36
|
+
- lib/ruby_lsp_proxy/proxy_session.rb
|
|
37
|
+
- lib/ruby_lsp_proxy/version.rb
|
|
38
|
+
homepage: https://github.com/yasuhiroki/ruby-lsp-proxy
|
|
39
|
+
licenses:
|
|
40
|
+
- MIT
|
|
41
|
+
metadata:
|
|
42
|
+
source_code_uri: https://github.com/yasuhiroki/ruby-lsp-proxy
|
|
43
|
+
rdoc_options: []
|
|
44
|
+
require_paths:
|
|
45
|
+
- lib
|
|
46
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
- - ">="
|
|
49
|
+
- !ruby/object:Gem::Version
|
|
50
|
+
version: 3.3.0
|
|
51
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
52
|
+
requirements:
|
|
53
|
+
- - ">="
|
|
54
|
+
- !ruby/object:Gem::Version
|
|
55
|
+
version: '0'
|
|
56
|
+
requirements: []
|
|
57
|
+
rubygems_version: 3.6.9
|
|
58
|
+
specification_version: 4
|
|
59
|
+
summary: Transparent stdio LSP proxy for running ruby-lsp inside Docker containers
|
|
60
|
+
test_files: []
|