Module: Rfmt::LSP::URI

Defined in:
lib/rfmt/lsp/uri.rb

Class Method Summary collapse

Class Method Details

.file_uri_to_path(uri) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/rfmt/lsp/uri.rb', line 10

def file_uri_to_path(uri)
  parsed = ::URI.parse(uri)
  return nil unless parsed.scheme == 'file'

  percent_decode(parsed.path)
rescue ::URI::InvalidURIError
  nil
end

.path_to_file_uri(path) ⇒ Object



19
20
21
# File 'lib/rfmt/lsp/uri.rb', line 19

def path_to_file_uri(path)
  "file://#{percent_encode(File.expand_path(path))}"
end

.percent_decode(value) ⇒ Object



23
24
25
# File 'lib/rfmt/lsp/uri.rb', line 23

def percent_decode(value)
  value.gsub(/%[0-9A-Fa-f]{2}/) { |match| [match[1..].to_i(16)].pack('C') }
end

.percent_encode(value) ⇒ Object



27
28
29
30
31
32
# File 'lib/rfmt/lsp/uri.rb', line 27

def percent_encode(value)
  value.bytes.map do |byte|
    char = byte.chr
    char.match?(%r{[A-Za-z0-9._~/-]}) ? char : format('%%%02X', byte)
  end.join
end