Skip to content
Open
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
26 changes: 18 additions & 8 deletions patchwork/common/tools/grep_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def json_schema(self) -> dict:
"name": "find_text",
"description": f"""\
Tool to find text in a file or files in a directory using a pattern based on the Unix shell style.
The current working directory is always {self.__working_dir}.
The current working directory is always {self.__working_dir}.
The path provided should either be absolute or relative to the current working directory.

This tool will match each line of the file with the provided pattern and prints the line number and the line content.
Expand All @@ -135,19 +135,26 @@ def json_schema(self) -> dict:
[!seq] matches any char not in seq

Example:
* '*macs' will match the file '.emacs'
* '*.py' will match all files with the '.py' extension
* 'class T*' will match the line 'class Team:' but not ' class Team:' because the second line is indented.
* '*var1: str' will match the line ' var1: str' but not 'var1: str = "test"'
* '*class Team*' will match both the lines 'class Team:' and 'class TeamMember(BaseTeam):'
* 'TeamMember' will not match 'class TeamMember:' because the pattern should match the entire line

""",
"type": "string",
},
"path": {
"description": """\
The path to the file to find text in.
The path to the file to find text in.
If not given, will search all file content in the current working directory.
If the path is a directory, will search all file content in the directory.
""",
"type": "string",
},
"recursive": {
"description": "Set as False to only search specified file or immediate files in the specified directory. Default is True.",
"type": "boolean",
},
"is_case_sensitive": {
"description": "Whether the pattern should be case-sensitive.",
"type": "boolean",
Expand All @@ -162,6 +169,7 @@ def execute(
pattern: Optional[str] = None,
path: Optional[Path] = None,
is_case_sensitive: bool = False,
recursive: bool = True,
) -> str:
if pattern is None:
return "`pattern` argument is required!"
Expand All @@ -176,12 +184,14 @@ def execute(
try:
path = Path(path).resolve()
except FileNotFoundError:
return f"`path` does not exist"
return "`path` does not exist"
if not path.is_relative_to(self.__working_dir):
return f"Path must be relative to working dir {self.__working_dir}"

if path.is_file():
paths = [path]
elif recursive:
paths = list(set(p for p in path.rglob("*") if p.is_file()))
else:
paths = [p for p in path.iterdir() if p.is_file()]

Expand All @@ -200,17 +210,17 @@ def execute(
content = f"Line {i + 1}: {self.__CHAR_LIMIT_TEXT}"

file_matches[str(path)].append(content)
except Exception as e:
except Exception:
pass

total_file_matches = ""
for path_str, matches in file_matches.items():
total_file_matches += f"\nPattern matches found in '{path}':\n" + "\n".join(matches)
total_file_matches += f"\nPattern matches found in '{path_str}':\n" + "\n".join(matches)

if len(total_file_matches) <= 5000:
return total_file_matches

total_file_matches = ""
for path_str, matches in file_matches.items():
total_file_matches += f"\n {len(matches)} Pattern matches found in '{path}': <TRUNCATED>\n"
total_file_matches += f"\n {len(matches)} Pattern matches found in '{path_str}': <TRUNCATED>\n"
return total_file_matches
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "patchwork-cli"
version = "0.0.120"
version = "0.0.121"
description = ""
authors = ["patched.codes"]
license = "AGPL"
Expand Down
36 changes: 36 additions & 0 deletions tests/cicd/generate_docstring/cpp_test_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,27 @@


template<typename T>
/**
* Adds two values of any type that supports the addition operator.
*
* @param a The first value to add.
* @param b The second value to add.
* @return The sum of the two values.
*/
T a_plus_b(T a, T b) {
return a + b;
}


/**
* Executes a SQL query on the given SQLite database and retrieves the result set.
*
* @param db Pointer to an SQLite database object.
* @param query SQL query string to be executed.
* @return A vector of vectors of strings, where each inner vector represents a row from the result set,
* and each string in the row represents a column value in that row. If the query fails to execute,
* an empty vector is returned.
*/
std::vector<std::vector<std::string>> sqlite(sqlite3* db, const std::string& query) {
std::vector<std::vector<std::string>> results;
sqlite3_stmt* stmt;
Expand Down Expand Up @@ -38,6 +54,20 @@ std::vector<std::vector<std::string>> sqlite(sqlite3* db, const std::string& que


template<typename T, typename F>
/**
* Compares two items using a key mapping function and returns an integer
* based on the result of the comparison. The function maps each item to
* a key value, then compares these key values to determine the order.
*
* @param key_map A function or callable object that extracts a comparison key
* from each item. This function takes an item of type T as input
* and returns a value that can be compared.
* @param item1 The first item to be compared.
* @param item2 The second item to be compared.
* @return An integer: -1 if the key of item1 is less than the key of item2,
* 1 if the key of item1 is greater than the key of item2,
* and 0 if both keys are equal.
*/
int compare(F key_map, const T& item1, const T& item2) {
auto val1 = key_map(item1);
auto val2 = key_map(item2);
Expand All @@ -48,6 +78,12 @@ int compare(F key_map, const T& item1, const T& item2) {
}


/**
* Generates a random string consisting of alphabetic characters (both uppercase and lowercase).
*
* @param length The length of the random string to generate.
* @return A random string of the specified length consisting of alphabetic characters.
*/
std::string random_alphabets(int length) {
static const std::string chars =
"abcdefghijklmnopqrstuvwxyz"
Expand Down
18 changes: 18 additions & 0 deletions tests/cicd/generate_docstring/java_test_file.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,26 @@
class Test {
/**
* Computes the sum of two integers.
*
* @param a The first integer to be summed.
* @param b The second integer to be summed.
* @return The sum of the two integers a and b.
*/

public static int a_plus_b(Integer a, Integer b) {
return a + b;
}

/**
* Compares two objects using a provided key mapping function and returns an integer value
* indicating the order.
*
* @param keymap A function that maps an object to a comparable value for comparison.
* @param a The first object to compare.
* @param b The second object to compare.
* @return -1 if the comparable value of a is less than that of b, 1 if greater,
* and 0 if they are equal.
*/
public static int a_plus_b(Function<Object, Comparable> keymap, object a, Object b) {
if (keymap(a) < keymap(b)) {
return -1;
Expand Down
21 changes: 21 additions & 0 deletions tests/cicd/generate_docstring/js_test_file.py.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@

/**
* Calculates the sum of two numbers.
* @param {number} a - The first number to be added.
* @param {number} b - The second number to be added.
* @returns {number} The sum of the two numbers.
*/
function a_plus_b(a, b) {
return a + b;
}

/**
* Compares two objects based on the value of a specified property.
* @param {string} keymap - The property name used for comparison.
* @param {Object} a - The first object to be compared.
* @param {Object} b - The second object to be compared.
* @returns {number} Returns -1 if the value of the specified property in the first object is less than
* the second, 1 if it is greater, and 0 if they are equal.
*/
const compare = function (keymap, a, b) {
if (a[keymap] < b[keymap]) {
return -1;
Expand All @@ -13,6 +27,13 @@ const compare = function (keymap, a, b) {
}
}

/**
* Executes a SQL query on the provided database using each row as input to the specified callback function.
* @param {Object} db - The SQLite database instance on which to execute the query.
* @param {string} query - The SQL query to be executed on the database.
* @param {Function} callback - The function to be called for each row returned by the query.
* @returns {void} No return value.
*/
const sqlite = (db, query, callback) => {
db.serialize(function () {
db.each(query, callback);
Expand Down
34 changes: 34 additions & 0 deletions tests/cicd/generate_docstring/kotlin_test_file.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,24 @@ import java.sql.ResultSet
import kotlin.random.Random


/**
* Adds two numbers of a generic type that extends Number and returns the result as a Double.
*
* @param a First number to add, must be of a type that extends Number.
* @param b Second number to add, must be of a type that extends Number.
* @return The sum of the two numbers as a Double.
*/
fun <T : Number> aPlusB(a: T, b: T): Double = a.toDouble() + b.toDouble()


/**
* Executes a SQL query on a given SQLite database connection and returns the result as a list of rows,
* where each row is represented as a list of objects corresponding to the columns in the result set.
*
* @param db The database connection used to execute the query.
* @param query The SQL query string to be executed.
* @return A list of lists, where each inner list represents a row in the query result, containing objects for each column.
*/
fun sqlite(db: Connection, query: String): List<List<Any?>> {
db.createStatement().use { statement ->
statement.executeQuery(query).use { resultSet ->
Expand All @@ -27,6 +42,18 @@ fun sqlite(db: Connection, query: String): List<List<Any?>> {
}


/**
* Compares two items based on a key extracted by the provided key mapping function.
* Returns -1 if the key of the first item is less than the key of the second item,
* 1 if it is greater, and 0 if they are equal.
*
* @param <T> The type of the items to be compared.
* @param <R> The type of the key, which must be comparable.
* @param keyMap A function that maps an item to its key for comparison.
* @param item1 The first item to be compared.
* @param item2 The second item to be compared.
* @return An integer -1, 0, or 1 based on the comparison of the keys.
*/
fun <T, R : Comparable<R>> compare(keyMap: (T) -> R, item1: T, item2: T): Int {
return when {
keyMap(item1) < keyMap(item2) -> -1
Expand All @@ -36,6 +63,13 @@ fun <T, R : Comparable<R>> compare(keyMap: (T) -> R, item1: T, item2: T): Int {
}


/**
* Generates a random string composed of alphabetic characters (both uppercase and lowercase)
* with a specified length.
*
* @param length The length of the resulting random alphabetic string.
* @return A string of randomly selected alphabetic characters with the specified length.
*/
fun randomAlphabets(length: Int): String {
val charPool = ('a'..'z') + ('A'..'Z')
return (1..length)
Expand Down
37 changes: 37 additions & 0 deletions tests/cicd/generate_docstring/python_test_file.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,43 @@
# fmt: off
def a_plus_b(a, b):
"""Calculates the sum of two numbers.

Args:
a (int or float): The first number.
b (int or float): The second number.

Returns:
int or float: The sum of the two numbers.
"""
return a + b


def sqlite(db, query):
"""Executes a given SQL query on the provided SQLite database connection and returns the results.

Args:
db (sqlite3.Connection): A SQLite database connection object.
query (str): A SQL query string to execute on the database.

Returns:
list: A list of tuples containing the result set of the executed query.
"""
cursor = db.cursor()
cursor.execute(query)
return cursor.fetchall()


def compare(key_map, item1, item2):
"""Compares two items based on a key function and returns an integer for sorting purposes.

Args:
key_map function: A function applied to each item to extract comparison keys.
item1 Any: The first item to compare.
item2 Any: The second item to compare.

Returns:
int: -1 if item1 is less than item2, 1 if item1 is greater than item2, 0 if they are equal.
"""
if key_map(item1) < key_map(item2):
return -1
elif key_map(item1) > key_map(item2):
Expand All @@ -21,4 +49,13 @@ def compare(key_map, item1, item2):
def random_alphabets(
length: int
):
"""Generate a random string of alphabetic characters.

Args:
length (int): The length of the string to generate.

Returns:
str: A string containing random alphabetical characters of the specified length.
"""

return ''.join(random.choices(string.ascii_letters, k=length))