Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GoToRelevantFile functionality #2985

Merged
merged 3 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/ruby_lsp/internal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
require "ruby_lsp/requests/document_symbol"
require "ruby_lsp/requests/folding_ranges"
require "ruby_lsp/requests/formatting"
require "ruby_lsp/requests/go_to_relevant_file"
require "ruby_lsp/requests/hover"
require "ruby_lsp/requests/inlay_hints"
require "ruby_lsp/requests/on_type_formatting"
Expand Down
87 changes: 87 additions & 0 deletions lib/ruby_lsp/requests/go_to_relevant_file.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# typed: strict
# frozen_string_literal: true

module RubyLsp
module Requests
# GoTo Relevant File is a custom [LSP
# request](https://microsoft.github.io/language-server-protocol/specification#requestMessage)
# that navigates to the relevant file for the current document.
# Currently, it supports source code file <> test file navigation.
class GoToRelevantFile < Request
extend T::Sig

TEST_KEYWORDS = ["test", "spec", "integration_test"]

TEST_PREFIX_PATTERN = /^(#{TEST_KEYWORDS.join("_|")}_)/
TEST_SUFFIX_PATTERN = /(_#{TEST_KEYWORDS.join("|_")})$/
TEST_PATTERN = /#{TEST_PREFIX_PATTERN}|#{TEST_SUFFIX_PATTERN}/

TEST_PREFIX_GLOB = T.let("#{TEST_KEYWORDS.join("_,")}_", String)
TEST_SUFFIX_GLOB = T.let("_#{TEST_KEYWORDS.join(",_")}", String)

#: (String path, String workspace_path) -> void
def initialize(path, workspace_path)
super()

@workspace_path = workspace_path
@path = T.let(path.delete_prefix(workspace_path), String)
end

# @override
#: -> Array[String]
def perform
find_relevant_paths
end

private

#: -> Array[String]
def find_relevant_paths
candidate_paths = Dir.glob(File.join("**", relevant_filename_pattern))
return [] if candidate_paths.empty?

find_most_similar_with_jaccard(candidate_paths).map { File.join(@workspace_path, _1) }
end

#: -> String
def relevant_filename_pattern
input_basename = File.basename(@path, File.extname(@path))

relevant_basename_pattern =
if input_basename.match?(TEST_PATTERN)
input_basename.gsub(TEST_PATTERN, "")
else
"{{#{TEST_PREFIX_GLOB}}#{input_basename},#{input_basename}{#{TEST_SUFFIX_GLOB}}}"
end

"#{relevant_basename_pattern}#{File.extname(@path)}"
end

# Using the Jaccard algorithm to determine the similarity between the
# input path and the candidate relevant file paths.
# Ref: https://en.wikipedia.org/wiki/Jaccard_index
# The main idea of this algorithm is to take the size of interaction and divide
# it by the size of union between two sets (in our case the elements in each set
# would be the parts of the path separated by path divider.)
#: (Array[String] candidates) -> Array[String]
def find_most_similar_with_jaccard(candidates)
dirs = get_dir_parts(@path)

_, results = candidates
.group_by do |other_path|
other_dirs = get_dir_parts(other_path)
# Similarity score between the two directories
(dirs & other_dirs).size.to_f / (dirs | other_dirs).size
end
.max_by(&:first)

results || []
end

#: (String path) -> Set[String]
def get_dir_parts(path)
Set.new(File.dirname(path).split(File::SEPARATOR))
end
end
end
end
22 changes: 22 additions & 0 deletions lib/ruby_lsp/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ def process_message(message)
discover_tests(message)
when "rubyLsp/resolveTestCommands"
resolve_test_commands(message)
when "experimental/goToRelevantFile"
experimental_go_to_relevant_file(message)
when "$/cancelRequest"
@global_state.synchronize { @cancelled_requests << message[:params][:id] }
when nil
Expand Down Expand Up @@ -291,6 +293,7 @@ def run_initialize(message)
experimental: {
addon_detection: true,
compose_bundle: true,
go_to_relevant_file: true,
},
),
serverInfo: {
Expand Down Expand Up @@ -1141,6 +1144,25 @@ def text_document_show_syntax_tree(message)
send_message(Result.new(id: message[:id], response: response))
end

#: (Hash[Symbol, untyped] message) -> void
def experimental_go_to_relevant_file(message)
path = message.dig(:params, :textDocument, :uri).to_standardized_path
unless path.nil? || path.start_with?(@global_state.workspace_path)
send_empty_response(message[:id])
return
end

unless path
send_empty_response(message[:id])
return
end

response = {
locations: Requests::GoToRelevantFile.new(path, @global_state.workspace_path).perform,
}
send_message(Result.new(id: message[:id], response: response))
end

#: (Hash[Symbol, untyped] message) -> void
def text_document_prepare_type_hierarchy(message)
params = message[:params]
Expand Down
2 changes: 2 additions & 0 deletions project-words
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ ipairs
Ispec
Itest
ivar
jaccard
Jaccard
Jaro
Kaigi
klass
Expand Down
154 changes: 154 additions & 0 deletions test/requests/go_to_relevant_file_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# typed: true
# frozen_string_literal: true

require "test_helper"

class GoToRelevantFileTest < Minitest::Test
def test_when_input_is_test_file_returns_array_of_implementation_file_locations
stub_glob_pattern("**/go_to_relevant_file.rb", ["lib/ruby_lsp/requests/go_to_relevant_file.rb"])

test_file_path = "/workspace/test/requests/go_to_relevant_file_test.rb"
expected = ["/workspace/lib/ruby_lsp/requests/go_to_relevant_file.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_file_path, "/workspace").perform
assert_equal(expected, result)
end

def test_when_input_is_implementation_file_returns_array_of_test_file_locations
pattern =
"**/{{test_,spec_,integration_test_}go_to_relevant_file,go_to_relevant_file{_test,_spec,_integration_test}}.rb"
stub_glob_pattern(pattern, ["test/requests/go_to_relevant_file_test.rb"])

impl_path = "/workspace/lib/ruby_lsp/requests/go_to_relevant_file.rb"
expected = ["/workspace/test/requests/go_to_relevant_file_test.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(impl_path, "/workspace").perform
assert_equal(expected, result)
end

def test_return_all_file_locations_that_have_the_same_highest_coefficient
pattern = "**/{{test_,spec_,integration_test_}some_feature,some_feature{_test,_spec,_integration_test}}.rb"
matches = [
"test/unit/some_feature_test.rb",
"test/integration/some_feature_test.rb",
]
stub_glob_pattern(pattern, matches)

impl_path = "/workspace/lib/ruby_lsp/requests/some_feature.rb"
expected = [
"/workspace/test/unit/some_feature_test.rb",
"/workspace/test/integration/some_feature_test.rb",
]

result = RubyLsp::Requests::GoToRelevantFile.new(impl_path, "/workspace").perform
assert_equal(expected.sort, result.sort)
end

def test_return_empty_array_when_no_filename_matches
pattern = "**/{{test_,spec_,integration_test_}nonexistent_file,nonexistent_file{_test,_spec,_integration_test}}.rb"
stub_glob_pattern(pattern, [])

file_path = "/workspace/lib/ruby_lsp/requests/nonexistent_file.rb"
result = RubyLsp::Requests::GoToRelevantFile.new(file_path, "/workspace").perform
assert_empty(result)
end

def test_it_finds_implementation_when_file_has_test_suffix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/test/feature_test.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_implementation_when_file_has_spec_suffix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/spec/feature_spec.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_implementation_when_file_has_integration_test_suffix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/test/feature_integration_test.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_implementation_when_file_has_test_prefix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/test/test_feature.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_implementation_when_file_has_spec_prefix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/test/spec_feature.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_implementation_when_file_has_integration_test_prefix
stub_glob_pattern("**/feature.rb", ["lib/feature.rb"])

test_path = "/workspace/test/integration_test_feature.rb"
expected = ["/workspace/lib/feature.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(test_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_tests_for_implementation
pattern = "**/{{test_,spec_,integration_test_}feature,feature{_test,_spec,_integration_test}}.rb"
stub_glob_pattern(pattern, ["test/feature_test.rb"])

impl_path = "/workspace/lib/feature.rb"
expected = ["/workspace/test/feature_test.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(impl_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_specs_for_implementation
pattern = "**/{{test_,spec_,integration_test_}feature,feature{_test,_spec,_integration_test}}.rb"
stub_glob_pattern(pattern, ["spec/feature_spec.rb"])

impl_path = "/workspace/lib/feature.rb"
expected = ["/workspace/spec/feature_spec.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(impl_path, "/workspace").perform
assert_equal(expected, result)
end

def test_it_finds_integration_tests_for_implementation
pattern = "**/{{test_,spec_,integration_test_}feature,feature{_test,_spec,_integration_test}}.rb"
stub_glob_pattern(pattern, ["test/feature_integration_test.rb"])

impl_path = "/workspace/lib/feature.rb"
expected = ["/workspace/test/feature_integration_test.rb"]

result = RubyLsp::Requests::GoToRelevantFile.new(impl_path, "/workspace").perform
assert_equal(expected, result)
end

private

def stub_glob_pattern(pattern, matches)
Dir.stubs(:glob).with(pattern).returns(matches)
end
end
15 changes: 15 additions & 0 deletions vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,23 @@
"command": "rubyLsp.fileOperation",
"when": "rubyLsp.activated && view == 'workbench.explorer.fileView'",
"group": "navigation"
},
{
"command": "rubyLsp.goToRelevantFile",
"when": "rubyLsp.activated && view == 'workbench.explorer.fileView'",
"group": "navigation"
}
],
"explorer/context": [
{
"command": "rubyLsp.fileOperation",
"when": "rubyLsp.activated",
"group": "2_workspace"
},
{
"command": "rubyLsp.goToRelevantFile",
"when": "rubyLsp.activated",
"group": "2_workspace"
}
]
},
Expand Down Expand Up @@ -159,6 +169,11 @@
"category": "Ruby LSP",
"icon": "$(ruby)"
},
{
"command": "rubyLsp.goToRelevantFile",
"title": "Go to relevant file (test <> source code)",
"category": "Ruby LSP"
},
{
"command": "rubyLsp.collectRubyLspInfo",
"title": "Collect Ruby LSP information for issue reporting",
Expand Down
8 changes: 8 additions & 0 deletions vscode/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,14 @@ export default class Client extends LanguageClient implements ClientInterface {
return super.dispose(timeout);
}

async sendGoToRelevantFileRequest(
uri: vscode.Uri,
): Promise<{ locations: string[] } | null> {
return this.sendRequest("experimental/goToRelevantFile", {
textDocument: { uri: uri.toString() },
});
}

private async benchmarkMiddleware<T>(
type: string | MessageSignature,
params: any,
Expand Down
1 change: 1 addition & 0 deletions vscode/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export enum Command {
StartServerInDebugMode = "rubyLsp.startServerInDebugMode",
ShowOutput = "rubyLsp.showOutput",
MigrateLaunchConfiguration = "rubyLsp.migrateLaunchConfiguration",
GoToRelevantFile = "rubyLsp.goToRelevantFile",
}

export interface RubyInterface {
Expand Down
14 changes: 14 additions & 0 deletions vscode/src/rubyLsp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,20 @@ export class RubyLsp {
);
},
),
vscode.commands.registerCommand(Command.GoToRelevantFile, async () => {
const uri = vscode.window.activeTextEditor?.document.uri;
if (!uri) {
return;
}
const response: { locations: string[] } | null | undefined =
await this.currentActiveWorkspace()?.lspClient?.sendGoToRelevantFileRequest(
uri,
);

if (response) {
return openUris(response.locations);
}
}),
];
}

Expand Down
Loading
Loading