Skills
Common GraphSitter code snippets
activity_definition_constant_extractor
Finds all @activity.defn(...)
decorators on functions and
If they have a name arg, it pulls out this value into a constants.py
file in the same directory, then imports it
and replaces the arg to point to this constant.
add_copyright_header_skill
Add a copyright header to all files in the codebase
add_decorator_to_foo_functions_skill
This skill adds a specified decorator to all functions within a codebase that start with a particular prefix, ensuring that the decorator is properly imported if not already present.
add_decorator_to_function
Adds a specified decorator to all functions and methods in a codebase, ensuring that it is not already present, and handles the necessary imports for the decorator.
add_docstrings_skill
This skill adds docstrings to all functions and methods in a codebase, ensuring that each function has a descriptive comment explaining its purpose and functionality.
add_return_type_hint_skill
Adds an integer return type hint to all functions whose names start with βfooβ.
add_self_parameter_to_skill_impl_methods
This codemod finds all methods that have the @skill_impl decorator on them and adds a first self
parameter
to the method.
add_type_hints_skill
This skill adds type hints to function parameters and return values in a codebase, enhancing type safety and improving code readability.
add_wrapper_function_skill
Adds a trivial wrapper function around each function and class method, creating a new function that simply calls the original function.
append_parameter_skill
Appends a parameter to the signature of a specified function in both Python and TypeScript codebases.
append_to_global_list
Skill to append 2 to global list variable βaβ.
append_type_to_union_type_skill
Appends an additional βstrβ type to a piped union type in Python
asyncify_function_skill
Given a synchronous function βfunc_to_convertβ, convert its signature to be asynchronous. The functionβs call sites as well as the call sitesβ functions are recursively converted as well.
asyncify_type_alias_elements
Given a type alias βMyMapperβ containing synchronous methods, convert βgetFromMethodβ method to be asynchronous. The inherited implementations of the type alias as well as all their call sites are also update.
call_graph_filter
This skill shows a visualization of the call graph from a given function or symbol. It iterates through the usages of the starting function and its subsequent calls, creating a directed graph of function calls. The skill filters out test files and includes only methods with specific names (post, get, patch, delete). By default, the call graph uses red for the starting node, yellow for class methods, and can be customized based on user requests. The graph is limited to a specified depth to manage complexity. In its current form, it ignores recursive calls and external modules but can be modified trivially to include them
call_graph_from_node
This skill creates a directed call graph for a given function. Starting from the specified function, it recursively iterates through its function calls and the functions called by them, building a graph of the call paths to a maximum depth. The root of the directed graph is the starting function, each node represents a function call, and edge from node A to node B indicates that function A calls function B. In its current form, it ignores recursive calls and external modules but can be modified trivially to include them. Furthermore, this skill can easily be adapted to support creating a call graph for a class method. In order to do this one simply needs to replace
function_to_trace = codebase.get_function("function_to_trace")
with
function_to_trace = codebase.get_class("class_of_method_to_trace").get_method("method_to_trace")
call_paths_between_nodes
This skill generates and visualizes a call graph between two specified functions. It starts from a given function and iteratively traverses through its function calls, building a directed graph of the call paths. The skill then identifies all simple paths between the start and end functions, creating a subgraph that includes only the nodes in these paths.
By default, the call graph uses blue for the starting node and red for the ending node, but these colors can be customized based on user preferences. The visualization provides a clear representation of how functions are interconnected, helping developers understand the flow of execution and dependencies between different parts of the codebase.
In its current form, it ignores recursive calls and external modules but can be modified trivially to include them
clear_global_list
Skill to clear global list variable βaβ.
codebase_path_refactorer
This codemod (code modification tool) script is designed to automate a mass refactor in a whole codebase by replacing instances of a specific string. It examines all files in the codebase, checking for any occurrences of the string β/appβ. It then scans through all the symbols inside each file, excluding import symbols. It next looks for appearances of β/appβ in the symbolβs source using a precise search. If it finds any occurrences, they are replaced with the string βpaths.appβ. In doing this, it simplifies the process of changing a directory path across a large number of files. The key features of this script are the ability to iterate over files and symbols within the files, and its ability to search and replace specific instances of a string.
convert_jsx_arrow_functions_to_named
This converts all JSX components that are arrow functions to named components.
convert_statement_to_argument
Converts http status code assertion statements into an expect_status
argument
for test functions that make a call to a http method.
convert_to_built_in_type_skill
Replaces type annotations using typing module with builtin types.
Examples: typing.List -> list typing.Dict -> dict typing.Set -> set typing.Tuple -> tuple
count_use_intl_functions_bar_chart
This counts the number of JSX components that have useIntl()
used as a hook in each child directory of src
, then plots it as a bar chart,
filtering for 0s
dead_code
This skill shows a visualization of the dead code in the codebase. It iterates through all functions in the codebase, identifying those that have no usages and are not in test files or decorated. These functions are considered βdead codeβ and are added to a directed graph. The skill then explores the dependencies of these dead code functions, adding them to the graph as well. This process helps to identify not only directly unused code but also code that might only be used by other dead code (second-order dead code). The resulting visualization provides a clear picture of potentially removable code, helping developers to clean up and optimize their codebase.
delete_rolled_out_feature_flag_skill
Locates a fully rolled out feature flag that has changed from a default value of False to True, and deletes all uses of the flag assuming the flag value is True. This skill simplifies conditional statements and removes unnecessary imports related to the feature flag.
delete_unused_logger_skill
Removes all global variables that are defined as logger instances if they are unused. This skill works for both Python and TypeScript codebases, with slight variations in the logger initialization pattern.
delete_unused_symbols_skill
Deletes all unused symbols in the codebase except for those starting with bar
(case insensitive) and deletes all files without any remaining symbols.
dict_to_schema
Converts a dictionary into a Schema object. Converts the key value pairs into arguments for the constructor
enum_attribute_mismatch_checker
None
enum_by_value_modifier
None
eslint_comment_skill
Remove eslint disable comments for an eslint rule. This is useful if a codebase is making an eslint rule either not required or reducing it to warning level. If the rule is no longer required/warning level, the disable comments are also no longer required and can be cleaned up.
export_skills
Convert default exports to named exports in TypeScript
extract_inline_props_type
I have a bunch of React components like this:
And I want to extract the props type like this:
So, that is, I want to extract the inlined props into their own type, then have the props be of this type.
file_app_import_graph
This skill visualizes the import relationships for a specific file in the codebase. It creates a directed graph where nodes represent the target file and its imported modules. Edges in the graph indicate the import relationships, pointing from the file to its imports. The skill focuses on a particular file (βpath/to/file.pyβ) and analyzes its import statements to construct the graph. This visualization helps developers understand the dependencies and structure of imports within the specified file, which can be useful for code organization and dependency management.
find_and_rename_loading_state_variable
This finds all instances of useState being assigned to a variable called loading
, i.e. const [loading, setLoading] = useState(false)
, and renames the variable loading
locally.
flag_and_rename
This skill uses both flag_ai and ai to flag and rename all functions that are incorrect or misleading. The first step is to use flag_ai to flag the functions that are incorrect or misleading. Then, the second step is to use ai to generate a new name for the function. Finally, the function is renamed in the codebase.
This is an example of how codebase.flag_ai and codebase.ai can be used together to achieve a more complex task.
flag_code
This skill uses flag_ai to flag all code that may have a potential bug. This is an example of Codebase AI being used to flag code that meets a certain criteria.
flag_plan_imports
This codemod looks through the codebase for all imports that import Plan
(a DB model) and flags the import.
foreign_key_graph
This skill helps analyze a data schema by creating a graph representation of SQLAlchemy models and their foreign key relationships.
It processes a collection of SQLAlchemy models with foreign keys referencing each other. All of these models are classes that inherit from BaseModel, similar to the one in this file. Foreign keys are typically defined in the following format: agent_run_id = Column(BigInteger, ForeignKey(βAgentRun.idβ, ondelete=βCASCADEβ), nullable=False)
The skill iterates through all classes in the codebase, identifying those that are subclasses of BaseModel. For each relevant class, it examines the attributes to find ForeignKey definitions. It then builds a mapping of these relationships.
Using this mapping, the skill constructs a directed graph where:
- Nodes represent the models (with the βModelβ suffix stripped from their names)
- Edges represent the foreign key relationships between models
This graph visualization allows for easy analysis of the data schema, showing how different models are interconnected through their foreign key relationships. The resulting graph can be used to understand data dependencies, optimize queries, or refactor the database schema.
fragment_to_shorthand_codemod
This codemod demonstrates the transition from Reactβs <Fragment />
to < />
.
It accomplishes this by iterating over all jsx_elements in the codebase and doing element.set_name(β¦).
It also does prop filtration by name on these elements.
In this specific scenario, where it was originally implemented, the remaining excess imports are automatically removed by the linter.
You could, however, accomplish this manually by iterating over all Imports in impacted files and doing imp.remove()
.
generate_docstrings
This skill generates docstrings for all class methods. This is another example of Codebase AI, where is it being used to generate textual content that will then be used as the docstring for the class methods.
This is also an example usecase of the context feature, where additional context is provided to the AI to help it generate the docstrings.
hook_inspector
For a given filename, print out all the hooks that are imported and differentiate between internal (user-defined code) and external (e.g. something defined by React)
if_statement_depth_logger
None
import_relationship_graph_visualizer
None
inconsistent_assignment_name_analyzer
This skill iterates through all functions in the codebase and identifies ones that are inconsistent in the value they get assigned when called as part of an assignment statement. For example, if a function foo() is frequently called and assigned to variables of different names, this would get printed out. Prints things out aesthetically
isolate_jsx_components
This codemod source code is designed to refactor a TypeScript codebase written with React (specifically .tsx
files that contain JSX). Its primary purpose is to isolate each JSX component function in its individual file.
The code first scans those TypeScript files in the codebase that end with β.tsxβ extension, indicating they contain JSX. Inside these files, it identifies JSX component functions and maps them to their associated file names in a dictionary. To do this, the code checks whether a function is a JSX component and checks if the component function has a valid (not None) name.
Following that, it iterates over each file identified earlier and for each JSX component in the file, constructs a new file path. If a file doesnβt already exist at the new file path, it generates a new file at that path, imports React, and then shifts the JSX component to this new file. It takes care to maintain all dependencies in the process.
If a file already exists for a component, it is not overwritten, and a message is printed to the console. The refactoring strategy used here is βupdate_all_importsβ which means that the codemod will update all locations where the moved function is imported.
By doing this, the codemod effectively splits up bulkier React files into separated ones, with each file containing a single JSX component, leading to a more organized and manageable codebase.
jsx_elements_collector
This codemod script scans through the entire codebase, identifies files that contain JSX elements and collates these JSX elements into a dictionary. This dictionary maintains a list of JSX element names for each source file path.
The script initially sets an empty dictionary. For each file in the codebase, it iterates through the JSX elements it contains. If the file path is not already present as a key in the dictionary, it initializes it with an empty list. It then adds the JSX elementβs name to this list, provided the name isnβt None.
Finally, the script iterates through the dictionary entries and prints the JSX elements grouped by file. Before printing, it filters out any None values from the list of JSX elements for each file. The output format is βFile: [filepath], JSX Elements: [names of the JSX elements separated by commas]β.
In essence, this script conveniently organizes and displays JSX element names on a per-file basis.
jsx_use_state_type_inferer
This finds all useState
calls within JSX components and tries to infer their type by looking at the value, then sets the generic passed to it.
mark_internal_functions_skill
This skill identifies functions that are exclusively used within the application directory and marks them as internal by appending an @internal tag to their docstrings.
migrate_imports_to_backward_compatible_versions
None
modify_test_files_for_uuid
This codemod script has a primary purpose of modifying test files in a codebase to replace hardcoded βspace-1β strings with call to a uuid() function. The uuid function provides a universally unique identifier which is desirable over hardcoded values for testing environments for uniqueness and non-predictability.
Key features of the script:
- Iterates over all files in the codebase.
- Checks if the active file is a test file and contains the string βspace-1β.
- If both conditions met, it then verifies if it already has βuuidβ import. If not, it adds the import statement from a specific module path.
- It then searches for occurrences of the hardcoded string βspace-1β in the test file and replaces them with a call to the uuid() function.
modularize_classes_in_codebase
This codemod skill script is designed to iterate over all files in a given codebase to improve the modularity and maintainability of the code. Its primary function is to move any classes that are extending from a superclass defined in the same file into their own separate files. However, it only processes files that are more than 500 lines long, skipping those that are shorter.
Starting its process, the script calculates the length of each file by splitting the content by line. If a file has fewer than 500 lines, it continues to the next. If a file is long enough, it examines each class within the file. For each class, it looks at the superclasses and checks if any of them are defined in the same file.
If a superclass is located in the same file as its child class, the script proceeds to move the child class into a new, separate file. It first builds the path for the new file, using the current directory and the name of the class, with the original fileβs extension. It then creates a new file at this path in the codebase, initially with an empty content. The child class is then moved into this new file, using the βupdate_all_importsβ strategy to ensure all references to the class are correctly updated. The script also provides feedback during its execution, printing out a message each time it moves a class to a new file.
This codemod skill script can be helpful in large codebases where class definitions may be tightly
most_common_use_state_variables
This aesthetically prints out a sorted list of the most common values that are used in a useState
as the state variable.
move_dataclasses_skills
Moves all classes decorated with @dataclasses into a dedicated directory
move_enums_to_separate_file_skill
Moves any enumerations found within a file into a separate file named enums.py
. If the original file
contains only enumerations, it renames that file to enums.py
. If the enums.py
file does not exist,
it creates one.
move_foo_functions_skill
Moves all functions starting with βfooβ to a file named foo
move_non_default_exported_jsx_components_skill
Moves all JSX components that are not exported by default into a new file located in the same directory as the original file.
react_component_render_map
For each react component in a specific file, print out the names of all components that it might render, skipping anonymous ones and tags like
etc.reduce_if_statement_condition_skill
Simplifies the if/else control flow by reducing conditions that are set to a specific value to True. This skill works for both Python and TypeScript codebases, with slight variations in the condition naming.
refactor_class
This skill refactors the given class to be shorter and more readable. It uses codebase to first find the class, then uses codebase AI to refactor the class. This is a trivial case of using Codebase AI to edit and generate new code that will then be applied to the codebase.
reinforce_data_schemas
The provided code is a Python script that dynamically analyzes and modifies the source code of a given Python program to introduce data classes for stronger data type enforcement.
In essence, itβs a Codemod utility that reinforces static typing in a codebase by introducing @dataclass
definitions into functions and call sites.
Key points:
-
At the start of the script, some constant like the function name and parameter name to analyze are declared. NOTE: Overridable attribute types and defaults for those attributes can also be defined.
-
The script proceeds to examine the identified function and its parameters in the codebase. If the function or parameters donβt exist, it raises an error.
-
It then iterates over all call sites of the function, accumulating arguments that match a dictionary data type.
-
The keys in all these dictionary arguments are analyzed to identify unique keys and their frequency.
-
Each unique key across all the dictionaries is then typed by inferring the value type associated with the key in the different call sites.
-
A
@dataclass
definition is then created with attributes that correspond to the unique keys identified and their inferred or overridden types. -
This
@dataclass
is injected into the source code, directly after the last import line. -
The function parameter type is adjusted to use this new
@dataclass
. -
Every call site of the function is then updated to initialize a new instance of this
@dataclass
in place of
relay_fragment_updater
None
remove_from_global_list
Skill to remove 2 from global list variable βaβ.
remove_unused_imports_skill
Removes all unused import statements from the codebase, ensuring that only necessary imports are retained in each file.
rename_class_skill
Renames a specified class in the codebase from an old name to a new name.
rename_foo_to_bar_skill
Renames all functions in the codebase that start with βfooβ to start with βbarβ, ensuring consistent naming conventions throughout the code.
rename_global_var_skill
Renames all global variables named βxβ to βyβ across the codebase.
rename_methods
This skill renames all class methods to something better. This is an example of Codebase AI generating content that is not directly written to the codebase as-in, but is chained and applied to the codebase in a later step.
In this case, the agent is asked to create a new name for each class method, then the new name is used to rename the method in the codebase.
rename_use_state_setter
This finds all calls to useState
hook in React where the setter is not just setXYZ
, where XYZ is the name of the state variable, and renames it.
Note that this does not handle the case where thereβs a collision between the setter name and another function defined in the component.
replace_aliased_wildcard_imports
This takes all imports in a given file that are imported via wildcard alias (and filters out lodash) and then
converts them to be explicit regular (non-wildcard) imports, making sure to update the imports accordingly. uses
the usage.match.parent.attribute
to get chained attributes from the wildcards.
repo_dir_tree
This skill displays the directory or repository tree structure of a codebase. It analyzes the file paths within the codebase and constructs a hierarchical representation of the directory structure. The skill creates a visual graph where each node represents a directory or file, and edges represent the parent-child relationships between directories. This visualization helps developers understand the overall organization of the codebase, making it easier to navigate and manage large projects. Additionally, it can be useful for identifying potential structural issues or inconsistencies in the project layout.
return_type_co_occurrence_matrix
Look at every union return type and find a co-occurrence matrix for the options, then print it out in a way thatβs easy to read. We will use this to find pairs that go together frequently and make more abstract types.
search_type_alias_inheritance_skill
Gets all implementation instances of type alias βMyMapperβ in TypeScript codebase.
set_global_var_value_skill
This skill modifies the values of all global variables in the codebase, setting them to 2 if their current assigned value is 1.
skill_language_distribution_analyzer
This codemod script scrutinizes a codebase to survey and count the functional skills that are implemented in Python and TypeScript. For every class in the codebase, it explores the methods for a β@skill_implβ decorator - a mark signifying an implemented skill.
If it finds such a decorator, it identifies the programming language used for the skill implementation by looking for βlanguage=ProgrammingLanguage.PYTHONβ or βlanguage=ProgrammingLanguage.TYPESCRIPTβ in the decoratorβs source.
The script creates a dictionary that maps each class (considered as a skill) to the languages that it supports (Python or TypeScript). The language support for each skill is represented with a corresponding emoji - a snake (π) for Python and a square (π¦) for TypeScript.
The script also counts the number of skills implemented in each language and prints these numbers. Finally, it displays the classes (skills) that only support Python but not TypeScript.
This script is beneficial for evaluating the language distribution across different skills in a mixed-languages codebase, and for identifying skills that should be upgraded to multi-language support.
skip_all_tests
This skill adds a decorator to all test functions in the codebase, marking them to be skipped during test execution with a specified reason.
sql_alchemy_eager_loading_optimizer
This codemod script is designed to analyze a codebase for SQLAlchemy relationships and optimize usage of eager loading in ORM queries. Purpose:
Its primary goal is to capture relationships defined using db.relationship
and to optimize the loading strategy from joinedload
to selectinload
when applicable. Functionality: 1. Relationship Extraction: The first step collects all relationships within the classes of the codebase,
specifically checking for the uselist
argument of db.relationship
to determine if the relationship represents a singular or multiple entities. 2.
Optimization of Load Strategies: The second step inspects function calls across files to identify usages of selectinload
and joinedload
. It
optimizes any joinedload
calls with uselist=True
by changing them to selectinload
, which enhances performance by reducing the number of queries.
Key Features: - It logs captured relationships for easy reference. - Automatically adjusts loading strategies for improved database querying
efficiency. - Ensures that the necessary imports for selectinload
are added when changes are made. Overall, the script aims to streamline ORM
queries in SQLAlchemy and improve application performance related to data loading strategies.
sql_alchemy_mapped_type_enhancer
The provided codemod script is designed to update SQLAlchemy model definitions by converting traditional column types into their mapped type
equivalents using Pythonβs typing system. Purpose: To enhance SQLAlchemy column definitions by adding type annotations for better type checking
and clarity in Python projects. Functionality: - It scans a specified directory for SQLAlchemy model classes. - It identifies attributes defined
using db.Column
and checks their types. - It maps standard SQLAlchemy column types to the new Mapped
type annotations using a predefined
dictionary. - It supports nullable types by wrapping them in Optional
. - It ensures that the necessary import statement for Mapped
is added if it
is not already present. Key Features: - Automatic conversion of SQLAlchemy column types to type-safe annotations. - Detection of nullable
attributes and appropriate wrapping in Optional
. - Preservation of existing structure while enhancing type safety. - Automated import management for
seamless integration with existing files.
temporal_activity_name_updater
Update temporal activity decorators.
- Finds all temporal βactivitiesβ (functions decorated with @activity.defn(β¦))
- For those that have a name= parameter in this decorator, replaces the value to add
my_directory
at the beginning if it starts with backfill
transaction_canonical_refactorer
None
unwrap_function_body
Unwraps the body of all functions in the codebase, transforming each functionβs code block into a flat structure without nested scopes.
unwrap_if_statement
Unwraps the body of all if statements in the file
unwrap_with_statement
This unwraps a with
statement
update_doc_string_of_decorated_methods
Updates the docstring of methods whose decorator has with_user/withUser in their name by appending βOPERATES ON USER DATAβ.
update_function_parameters_and_return_type
Sets the first 5 functions to have a new first parameter test
, the second 5 functions to have a new last parameter test
, and the next 5 functions to have return type null
.
update_optional_type_hints_skill
This skill replaces type hints in functions and methods by updating instances of Optional[type] to type | None, ensuring compatibility with modern type hinting practices.
use_suspense_query_refactor
This codemod script is designed to refactor a codebase that uses the βuseSuspenseQueryβ function from the @tanstack/react-query library to the βuseSuspenseQueriesβ function instead. It performs a few key steps:
-
Iterates over all files in the codebase, specifically focusing on files within the βsrcβ directory and ignoring files like β.eslint.rcβ.
-
For each file, it checks if βuseSuspenseQueryβ is present. If it isnβt, the file is skipped.
-
If βuseSuspenseQueryβ is found, an import statement for βuseQueryβ and βuseSuspenseQueriesβ from the @tanstack/react-query library is added to the file.
-
Then, it enters each function in the file and scans for assignment statements that use βuseSuspenseQueryβ. If any instances are found, it gathers the variable names and the arguments passed to βuseSuspenseQueryβ.
-
Once all instances of βuseSuspenseQueryβ are collected, they are replaced with calls to βuseSuspenseQueriesβ. The variable names and query arguments gathered earlier are used to structure the new function call.
-
Finally, the old βuseSuspenseQueryβ calls are replaced with the newly constructed βuseSuspenseQueriesβ calls, and the refactoring is complete.
The main purpose of this codemod script is to automate the process of refactoring code to use the new βuseSuspenseQueriesβ function
wrap_nested_arrow_functions_with_use_callback
This wraps all nested arrow functions in JSX components with useCallback
while constraining it to functions that are passed in as a prop to a JSX element in the current file.
write_test
This skill writes a test for the given function. This is an example of Codebase AI generating brand new code that will then be added to the codebase.