|
3 | 3 | import static org.slf4j.LoggerFactory.getLogger; |
4 | 4 |
|
5 | 5 | import java.io.IOException; |
| 6 | +import java.nio.charset.Charset; |
6 | 7 | import java.nio.file.Files; |
| 8 | +import java.nio.file.NoSuchFileException; |
7 | 9 | import java.nio.file.Path; |
8 | 10 | import java.nio.file.Paths; |
| 11 | +import java.nio.file.StandardCopyOption; |
9 | 12 | import java.util.Comparator; |
10 | 13 | import java.util.stream.Stream; |
11 | 14 | import org.slf4j.Logger; |
12 | 15 |
|
13 | 16 | public class GeminiTools { |
14 | 17 |
|
15 | 18 | private static final Logger log = getLogger(GeminiTools.class); |
| 19 | + private static final long MAX_FILE_SIZE = 1024 * 1024; // 1MB limit |
| 20 | + private static final String DEFAULT_ENCODING = "UTF-8"; |
16 | 21 |
|
17 | 22 | /** |
18 | 23 | * Lists the contents of a directory, including files and subdirectories |
@@ -88,6 +93,183 @@ public static String listFiles(String path, Boolean showHidden) { |
88 | 93 | } |
89 | 94 | } |
90 | 95 |
|
| 96 | + /** |
| 97 | + * Reads file contents from the filesystem. Supports both absolute and relative paths, various |
| 98 | + * encodings, and includes proper error handling and file size limits. |
| 99 | + * |
| 100 | + * @param path The file path to read (absolute or relative to current working directory) |
| 101 | + * @param encoding The character encoding to use (defaults to UTF-8 if null) |
| 102 | + * @return File contents or error message |
| 103 | + */ |
| 104 | + public static String readFile(String path, String encoding) { |
| 105 | + log.info("Executing readFile with path: {}, encoding: {}", path, encoding); |
| 106 | + |
| 107 | + try { |
| 108 | + // Handle default values |
| 109 | + String pathStr = path != null ? path : "."; |
| 110 | + String fileEncoding = encoding != null ? encoding : DEFAULT_ENCODING; |
| 111 | + |
| 112 | + Path filePath = resolveFilePath(pathStr); |
| 113 | + |
| 114 | + // Check file size before reading |
| 115 | + if (Files.exists(filePath)) { |
| 116 | + long fileSize = Files.size(filePath); |
| 117 | + if (fileSize > MAX_FILE_SIZE) { |
| 118 | + return "Error: File is too large (" |
| 119 | + + fileSize |
| 120 | + + " bytes). Maximum supported file size is " |
| 121 | + + MAX_FILE_SIZE |
| 122 | + + " bytes."; |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + // Read file content with specified encoding |
| 127 | + Charset charset = Charset.forName(fileEncoding); |
| 128 | + return Files.readString(filePath, charset); |
| 129 | + |
| 130 | + } catch (NoSuchFileException e) { |
| 131 | + return "Error: File not found: " + e.getFile(); |
| 132 | + } catch (SecurityException e) { |
| 133 | + return "Error: Permission denied accessing file: " + path; |
| 134 | + } catch (IOException e) { |
| 135 | + return "Error: IO exception reading file: " + e.getMessage(); |
| 136 | + } catch (IllegalArgumentException e) { |
| 137 | + return "Error: Invalid encoding specified: " + encoding; |
| 138 | + } catch (Exception e) { |
| 139 | + return "Error: Unexpected error reading file: " + e.getMessage(); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Performs simple text replacement in files. Creates a backup before editing and validates that |
| 145 | + * search text exists. |
| 146 | + * |
| 147 | + * @param path The path to the file to edit |
| 148 | + * @param searchText The text to search for and replace |
| 149 | + * @param replaceText The text to replace the search text with |
| 150 | + * @return Success message with replacement count or error message |
| 151 | + */ |
| 152 | + public static String editFile(String path, String searchText, String replaceText) { |
| 153 | + log.info( |
| 154 | + "Executing editFile with path: {}, searchText: {}, replaceText: {}", |
| 155 | + path, |
| 156 | + searchText, |
| 157 | + replaceText); |
| 158 | + |
| 159 | + try { |
| 160 | + // Validate required parameters |
| 161 | + if (path == null || path.trim().isEmpty()) { |
| 162 | + return "Error: 'path' parameter is required and cannot be empty"; |
| 163 | + } |
| 164 | + if (searchText == null || searchText.trim().isEmpty()) { |
| 165 | + return "Error: 'searchText' parameter is required and cannot be empty"; |
| 166 | + } |
| 167 | + if (replaceText == null) { |
| 168 | + return "Error: 'replaceText' parameter is required"; |
| 169 | + } |
| 170 | + |
| 171 | + // Validate path for security (prevent directory traversal) |
| 172 | + if (path.contains("..") |
| 173 | + || path.startsWith("/etc/") |
| 174 | + || path.startsWith("/usr/") |
| 175 | + || path.startsWith("/bin/")) { |
| 176 | + log.warn("Potentially unsafe path attempted: {}", path); |
| 177 | + return "Error: Path not allowed for security reasons"; |
| 178 | + } |
| 179 | + |
| 180 | + Path filePath; |
| 181 | + try { |
| 182 | + filePath = Paths.get(path); |
| 183 | + if (!filePath.isAbsolute()) { |
| 184 | + filePath = Paths.get(System.getProperty("user.dir")).resolve(path); |
| 185 | + } |
| 186 | + filePath = filePath.normalize(); |
| 187 | + } catch (Exception e) { |
| 188 | + log.error("Invalid path: {}", path, e); |
| 189 | + return "Error: Invalid file path: " + path; |
| 190 | + } |
| 191 | + |
| 192 | + // Check if file exists |
| 193 | + if (!Files.exists(filePath)) { |
| 194 | + log.error("File not found: {}", filePath); |
| 195 | + return "Error: File not found: " + path; |
| 196 | + } |
| 197 | + |
| 198 | + // Check if it's actually a file (not a directory) |
| 199 | + if (!Files.isRegularFile(filePath)) { |
| 200 | + log.error("Path is not a regular file: {}", filePath); |
| 201 | + return "Error: Path is not a regular file: " + path; |
| 202 | + } |
| 203 | + |
| 204 | + // Read current file content |
| 205 | + String content; |
| 206 | + try { |
| 207 | + content = Files.readString(filePath); |
| 208 | + } catch (IOException e) { |
| 209 | + log.error("Failed to read file: {}", filePath, e); |
| 210 | + return "Error: Failed to read file: " + e.getMessage(); |
| 211 | + } |
| 212 | + |
| 213 | + // Check if search text exists in the file |
| 214 | + if (!content.contains(searchText)) { |
| 215 | + log.info("Search text '{}' not found in file: {}", searchText, filePath); |
| 216 | + return "Error: Text '" + searchText + "' not found in file"; |
| 217 | + } |
| 218 | + |
| 219 | + // Count occurrences before replacement |
| 220 | + int occurrences = content.split(searchText, -1).length - 1; |
| 221 | + |
| 222 | + // Create backup file |
| 223 | + Path backupPath = Paths.get(filePath + ".backup"); |
| 224 | + try { |
| 225 | + Files.copy(filePath, backupPath, StandardCopyOption.REPLACE_EXISTING); |
| 226 | + log.info("Created backup file: {}", backupPath); |
| 227 | + } catch (IOException e) { |
| 228 | + log.error("Failed to create backup file: {}", backupPath, e); |
| 229 | + return "Error: Failed to create backup file: " + e.getMessage(); |
| 230 | + } |
| 231 | + |
| 232 | + // Perform replacement |
| 233 | + String newContent = content.replace(searchText, replaceText); |
| 234 | + |
| 235 | + // Write updated content back to file |
| 236 | + try { |
| 237 | + Files.writeString(filePath, newContent); |
| 238 | + log.info("Successfully edited file: {} ({} occurrences replaced)", filePath, occurrences); |
| 239 | + } catch (IOException e) { |
| 240 | + log.error("Failed to write updated content to file: {}", filePath, e); |
| 241 | + return "Error: Failed to write to file: " + e.getMessage(); |
| 242 | + } |
| 243 | + |
| 244 | + return String.format( |
| 245 | + "File edited successfully! Replaced %d occurrences of '%s' with '%s' in %s. Backup created at %s.backup", |
| 246 | + occurrences, searchText, replaceText, path, path); |
| 247 | + |
| 248 | + } catch (Exception e) { |
| 249 | + log.error("Unexpected error in editFile tool", e); |
| 250 | + return "Error: Unexpected error occurred: " + e.getMessage(); |
| 251 | + } |
| 252 | + } |
| 253 | + |
| 254 | + /** |
| 255 | + * Resolves the file path, handling both absolute and relative paths. Relative paths are resolved |
| 256 | + * against the current working directory. |
| 257 | + * |
| 258 | + * @param pathStr the path string to resolve |
| 259 | + * @return the resolved Path |
| 260 | + */ |
| 261 | + private static Path resolveFilePath(String pathStr) { |
| 262 | + Path path = Paths.get(pathStr); |
| 263 | + |
| 264 | + if (path.isAbsolute()) { |
| 265 | + return path; |
| 266 | + } else { |
| 267 | + // Resolve relative path against current working directory |
| 268 | + Path currentDir = Paths.get(System.getProperty("user.dir")); |
| 269 | + return currentDir.resolve(path); |
| 270 | + } |
| 271 | + } |
| 272 | + |
91 | 273 | private static String formatFileSize(long bytes) { |
92 | 274 | if (bytes < 1024) { |
93 | 275 | return bytes + " bytes"; |
|
0 commit comments