import marimo __generated_with = "0.9.14" app = marimo.App(width="medium") @app.cell def __(): import requests import json import sys from typing import Dict, Any, Optional, List from lsproxy import GetReferencesRequest, FileRange, Position import marimo as mo return ( Any, Dict, FileRange, GetReferencesRequest, List, Optional, Position, json, mo, requests, sys, ) @app.cell def __(mo): mo.md("""### Welcome to the `lsproxy` tutorial! We'll be showing you how you can use `lsproxy` to easily navigate and search another codebase using python. Let's get started!\n> We will be using an open-source repo to demonstrate `lsproxy`. We chose [Trieve](https://github.com/devflowinc/trieve), a rust-based infrastructure solution for search, recommendations and RAG. They have rust for their backend, and typescript to run multiple frontend interfaces. We love their product and their team, check them out!""") return @app.cell def __(mo): mo.md("""
""") return @app.cell def __(mo): # The first step is to create our API client from lsproxy import Lsproxy api_client = Lsproxy() mo.show_code() return Lsproxy, api_client @app.cell def __(mo): mo.md("""Other than starting the `lsproxy` docker container, no initialization is required to use `lsproxy`. Here, our "initialization" is just reading in the files to make the tutorial easier to navigate! Please click the button below to get started.""") return @app.cell def __(mo): start_button = mo.ui.run_button(label="Click to initialize") start_button return (start_button,) @app.cell def __(get_files, mo, start_button): # Reads all the files in the repo on initialization mo.stop(not start_button.value) file_symbol_dict = get_files() return (file_symbol_dict,) @app.cell def __(mo): mo.md("""""") return @app.cell def __(file_symbol_dict, mo): mo.stop(not file_symbol_dict) mo.md( """### `Example 1: Exploring symbols and their references in a file`\nYou'll see how easy it is to:\n\n- Get symbol definitions from a file.\n- Read the source code for any symbol.\n- Find references to the symbol across the codebase\n\nAlso note that we are only showing typescript and rust in this example, but we also support python!
\n---\n""" ) return @app.cell def __(selections_ex1): selections_ex1 return @app.cell def __(code_language_select_ex1, file_dropdown_ex1, mo): # This is just for controlling the flow of this tutorial mo.stop(not file_dropdown_ex1.value) selected_file_first_time = True code_language_ex1 = code_language_select_ex1.value selected_file_ex1 = file_dropdown_ex1.value return code_language_ex1, selected_file_ex1, selected_file_first_time @app.cell def __(code_language_ex1, mo, selected_file_first_time): # This is just for controlling the flow of this tutorial mo.stop(not selected_file_first_time) mo.md( f"Note that you selected a file in {code_language_ex1}, but `lsproxy` wraps language servers for all the supported languages, and routes your request to the right one, so you don't have to worry about configuring servers for each language. Go ahead and try a different language!" ) return @app.cell def __(api_client, mo, selected_file_ex1): # Retrieving the symbols defined in a file is just a single call symbols_ex1 = api_client.definitions_in_file(selected_file_ex1) mo.show_code() return (symbols_ex1,) @app.cell def __(mo, symbols_ex1): # Pack the data from the symbols into a tabular format table_data_ex1 = [ { "name": symbol.name, "kind": symbol.kind, "start_line": symbol.identifier_position.position.line, "start_character": symbol.identifier_position.position.character, "num_lines": symbol.range.end.line - symbol.range.start.line + 1, "index": i, } for i, symbol in enumerate(symbols_ex1) ] # Create the table element to display symbol_table_ex1 = mo.ui.table( data=table_data_ex1, page_size=10, selection="single", label="Now, select a symbol to view code and references", ) # Display the table symbol_table_ex1 return symbol_table_ex1, table_data_ex1 @app.cell def __(mo, symbol_table_ex1, symbols_ex1): mo.stop(not symbol_table_ex1.value) selected_symbol_ex1 = symbols_ex1[symbol_table_ex1.value[0].get("index")] return (selected_symbol_ex1,) @app.cell def __( FileRange, GetReferencesRequest, api_client, mo, selected_file_ex1, selected_symbol_ex1, ): # Read the source code for a particular range in a file by just asking for it! file_range_ex1 = FileRange( path=selected_file_ex1, start=selected_symbol_ex1.range.start, end=selected_symbol_ex1.range.end, ) source_code_ex1 = api_client.read_source_code(file_range_ex1).source_code # Get references to the symbol and optionally include context lines surrounding the usage reference_request_ex1 = GetReferencesRequest( identifier_position=selected_symbol_ex1.identifier_position, include_code_context_lines=2, ) reference_results_ex1 = api_client.find_references(reference_request_ex1) viewed_symbol = True mo.show_code() return ( file_range_ex1, reference_request_ex1, reference_results_ex1, source_code_ex1, viewed_symbol, ) @app.cell def __( code_language_ex1, mo, pretty_format_code_result, pretty_format_reference_results, reference_results_ex1, source_code_ex1, ): # Format the code and reference results for display code_text_ex1 = pretty_format_code_result(source_code_ex1, code_language_ex1) reference_text_ex1 = pretty_format_reference_results( reference_results_ex1, code_language_ex1 ) # Display the code and reference text mo.callout( mo.vstack( [ mo.md(code_text_ex1), mo.md(reference_text_ex1), ] ) ) return code_text_ex1, reference_text_ex1 @app.cell def __(mo, viewed_symbol): mo.stop(not viewed_symbol) example_2 = mo.ui.run_button(label="Click to move on to example 2: Exploring connections between files", full_width=True) example_2 return (example_2,) @app.cell def __(mo): mo.md("""""") return @app.cell def __(example_2, mo): mo.stop(not example_2.value) ex2_unlocked = True return (ex2_unlocked,) @app.cell def __(ex2_unlocked, mo, selections_2): mo.stop(not ex2_unlocked) mo.vstack([ mo.md("""### Example 2: Exploring connections between files\nThe examples above are similar to the kind of functionality you can find in your IDE, but having everything accessible with easy python functions means that you can compose these operations to be much more powerful.\n\nIn this example, we show:\n\n- Finding all the files that reference a given file\n- Tagging each file with the symbols it references\n\n---"""), selections_2, ]) return @app.cell def __(ex2_unlocked, file_dropdown_2, mo): mo.stop(not ex2_unlocked) # Pull the symbols inside a file selected_file_ex2 = file_dropdown_2.value return (selected_file_ex2,) @app.cell def __(api_client, mo, selected_file_ex2): # As before we can get all of the symbols from a file symbols_ex2 = api_client.definitions_in_file(selected_file_ex2) mo.show_code() return (symbols_ex2,) @app.cell def __( GetReferencesRequest, api_client, mo, selected_file_ex2, symbols_ex2, ): # But now we can repeatedly look for references on EVERY symbol in the file and build up a graph of the references referenced_symbols_in_file_dict = {} for symbol in mo.status.progress_bar( symbols_ex2, title="Symbols processed", remove_on_exit=True ): reference_request_ex2 = GetReferencesRequest( identifier_position=symbol.identifier_position, ) references_ex2 = api_client.find_references(reference_request_ex2).references # Save which symbols were referenced by which file for ref in references_ex2: referencing_file = ref.path if referencing_file != selected_file_ex2: referenced_symbols_in_file_dict.setdefault( (selected_file_ex2, referencing_file), set() ).add(symbol.name) mo.show_code() return ( ref, reference_request_ex2, referenced_symbols_in_file_dict, references_ex2, referencing_file, symbol, ) @app.cell def __(ex2_unlocked, mo): mo.stop(not ex2_unlocked) mo.md( "From this information we can build a simple graph showing how a file's symbols are referenced by other files in the codebase." ) return @app.cell def __(generate_reference_diagram, mo, referenced_symbols_in_file_dict): if not referenced_symbols_in_file_dict: mermaid_diagram = generate_reference_diagram("No external references found") else: mermaid_diagram = generate_reference_diagram(referenced_symbols_in_file_dict) diagram_shown = True mo.mermaid(mermaid_diagram) return diagram_shown, mermaid_diagram @app.cell def __(mo): mo.md("""""") return @app.cell def __(diagram_shown, mo): mo.stop(not diagram_shown) example_3 = mo.ui.run_button(label="Click to move on to example 3: Analyzing a change diff with call hierarchy.", full_width=True) example_3 return (example_3,) @app.cell def __(example_3, mo): mo.stop(not example_3.value) mo.md( """### Example 3 (Advanced): Analyzing a change diff with call hierarchy.\n We can compose definitions and references to identify the full code paths that are affected by a particular change, and uncover ripple effects through the codebase.\n\n---""" ) return @app.cell def __(example_3, mo): mo.stop(not example_3.value) import subprocess import io from pydantic import BaseModel mo.md("""Let's start with a diff of a change to the deletion logic in Trieve in this [PR](https://github.com/devflowinc/trieve/pull/2649)""") return BaseModel, io, subprocess @app.cell def __(mo, subprocess): parent_commit = "1910d6867877bfdd64ca822e266372335392a8be" # Load in the diff diff_text = subprocess.check_output( ["git", "diff", parent_commit], cwd="./trieve" ).decode("utf-8") mo.show_code(f"Output: Diff has {len(diff_text.splitlines())} lines") return diff_text, parent_commit @app.cell def __(example_3, mo): mo.stop(not example_3.value) mo.md("""First, we extract affected lines from the diff text.""") return @app.cell def __(Dict, List, Tuple, diff_text, io, mo): from unidiff import PatchSet def parse_diff(diff_text) -> Tuple[Dict[str, List[int]], str]: patch = PatchSet(io.StringIO(diff_text)) affected_lines = {} for patched_file in patch: for hunk in patched_file: for line in hunk: if line.is_added: affected_lines.setdefault(patched_file.path, set()).add( line.target_line_no ) elif line.is_removed: affected_lines.setdefault(patched_file.path, set()).add( line.source_line_no ) return affected_lines affected_lines = parse_diff(diff_text) mo.show_code( f"Output: Diff contains {sum([len(lines) for lines in affected_lines.values()])} changed lines in {len(affected_lines)} files." ) return PatchSet, affected_lines, parse_diff @app.cell def __(example_3, mo): mo.stop(not example_3.value) mo.md("""Then we define logic to \n\n 1. Find symbol definitions containing affected lines\n\n 2. Find references to these symbols.\n\n 3. Repeat with lines containing references, until we reach the end.\n\nWe also save the symbols that are direct parents of affected lines, so we can distinguish them from the symbols indirectly affected by the change.""") return @app.cell def __(BaseModel, GetReferencesRequest, List, Set, Tuple, api_client, mo): from lsproxy import FilePosition class HierarchyItem(BaseModel): name: str kind: str defined_at: FilePosition source_code: str def __hash__(self) -> int: return hash( ( self.defined_at.path, self.defined_at.position.line, self.defined_at.position.character, ) ) def get_symbols_containing_positions( target_positions: List[FilePosition], ) -> List[HierarchyItem]: file_path = target_positions[0].path ####################### ### Get definitions ### ####################### symbols = api_client.definitions_in_file(file_path) symbols_containing_position = { HierarchyItem( name=symbol.name, kind=symbol.kind, defined_at=symbol.identifier_position, source_code=api_client.read_source_code(symbol.range).source_code, ) for symbol in symbols for target_position in target_positions if symbol.range.contains(target_position) } return symbols_containing_position def propagate_changes_through_codebase(symbols_changed_directly: List[FilePosition]): """ Compute the chain of code symbols that touch the code at the starting positions. """ nodes: Set[HierarchyItem] = set() edges: Set[Tuple[HierarchyItem, HierarchyItem]] = set() # Initialize with symbols that contain the starting positions stack = list(symbols_changed_directly) while stack: symbol = stack.pop() # If we've already processesed this symbol skip it if symbol in nodes: continue nodes.add(symbol) # For each symbol we find all its references references = api_client.find_references( GetReferencesRequest( identifier_position=symbol.defined_at, include_declaration=False, ) ).references # Group them by file references_by_file = {} for ref in references: references_by_file.setdefault(ref.path, []).append(ref) # And then find symbols that contain the references so we can keep processing related_symbols = [ sym for refs in references_by_file.values() for sym in get_symbols_containing_positions(refs) ] for related_symbol in related_symbols: if related_symbol != symbol: edges.add((symbol, related_symbol)) stack.append(related_symbol) return nodes, edges mo.show_code() return ( FilePosition, HierarchyItem, get_symbols_containing_positions, propagate_changes_through_codebase, ) @app.cell def __( FilePosition, Position, affected_lines, api_client, get_symbols_containing_positions, mo, propagate_changes_through_codebase, ): affected_files = list(affected_lines.keys()) lsp_files = api_client.list_files() affected_code_files = filter(lambda file: file in lsp_files, affected_files) symbols_changed_directly = set() for file in affected_code_files: # For all the affected lines, we figure out what symbol they belong to affected_positions = [ FilePosition(path=file, position=Position(line=line, character=0)) for line in affected_lines[file] ] symbols_changed_directly.update(get_symbols_containing_positions(affected_positions)) # And then recursively follow the affected symbol through the codebase by following references all_nodes, all_edges = propagate_changes_through_codebase(symbols_changed_directly) mo.show_code() return ( affected_code_files, affected_files, affected_positions, all_edges, all_nodes, file, lsp_files, symbols_changed_directly, ) @app.cell def __( all_edges, all_nodes, hierarchy_to_mermaid, mo, symbols_changed_directly, ): mm = hierarchy_to_mermaid(all_nodes, all_edges, symbols_changed_directly) mo.vstack([ mo.md("### Call graph of the code affected by the change.\n #### The white nodes are present in the diff, while the red ones are affected indirectly."), mo.mermaid(mm) ]) return (mm,) @app.cell def __(HierarchyItem, Set, Tuple): def hierarchy_to_mermaid( nodes: Set[HierarchyItem], edges: Set[Tuple[HierarchyItem, HierarchyItem]], symbols_changed_directly: Set[HierarchyItem], ) -> str: """ Convert hierarchy nodes and edges to a Mermaid diagram string with subgraphs by file. Uses hash codes as node identifiers. Nodes that were changed directly are colored red. Args: nodes: Set of HierarchyItem objects representing code symbols edges: Set of tuples containing (from_symbol, to_symbol) relationships symbols_changed_directly: Set of HierarchyItem objects that were changed directly Returns: str: Mermaid diagram representation of the hierarchy with file-based subgraphs """ mermaid_lines = [ "%%{", " init: {", " 'flowchart': {", " 'rankSpacing': 100,", # Increase vertical space between ranks " 'nodeSpacing': 50,", # Increase horizontal space between nodes " 'padding': 20", # Add padding around the entire diagram " }", " }", "}%%", "graph TD", ] # Track nodes that need red styling direct_node_ids = set() indirect_node_ids = set() # Group nodes by file nodes_by_file = {} for node in nodes: file_path = node.defined_at.path if file_path not in nodes_by_file: nodes_by_file[file_path] = [] nodes_by_file[file_path].append(node) # Track node IDs that need to be colored red if node in symbols_changed_directly: direct_node_ids.add(f"node{abs(hash(node))}") else: indirect_node_ids.add(f"node{abs(hash(node))}") # Create subgraphs for each file for file_idx, (file_path, file_nodes) in enumerate(nodes_by_file.items()): # Create subgraph with unique ID subgraph_id = f"subgraph_{file_idx}" mermaid_lines.append(f" subgraph {subgraph_id}[{file_path}]") # Add nodes for this file for node in file_nodes: # Escape quotes and special characters in names escaped_name = node.name.replace('"', '\\"') # Add kind as a suffix in italics label = f'"{escaped_name}