
com.undefinedlabs.scope.utils.FileUtils Maven / Gradle / Ivy
package com.undefinedlabs.scope.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class FileUtils {
public static final int NOT_FOUND_LINE_NUMBER = -1;
private static final String CLASS_PREFIX = "class ";
private static final String METHOD_SUFFIX = "(";
/** Search file by filename going through current path and parents. */
public static File searchBackwardsByFilename(
final String startingPath, final String filenameToSearch) {
if (StringUtils.isEmpty(startingPath) || StringUtils.isEmpty(filenameToSearch)) {
return null;
}
File currentDir =
new File(startingPath.endsWith("/") ? startingPath : startingPath.concat("/"));
File[] currentFiles = new File[0];
while ((currentFiles == null || currentFiles.length == 0) && currentDir != null) {
currentFiles =
currentDir.listFiles(
new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.endsWith(filenameToSearch);
}
});
if (currentFiles == null || currentFiles.length == 0) {
currentDir = currentDir.getParent() != null ? new File(currentDir.getParent()) : null;
}
}
return currentFiles != null && currentFiles.length > 0 ? currentFiles[0] : null;
}
/**
* Find the line number based on a filepath, target class, and targetMethod. If it is not found,
* returns -1
*/
public static int resolveMethodLineNumber(
final String filepath, final String targetClassName, final String targetMethod) {
final String trimmedClassName = ClassNameUtils.INSTANCE.getMostInnerClassName(targetClassName);
if (StringUtils.isEmpty(filepath)
|| StringUtils.isEmpty(trimmedClassName)
|| StringUtils.isEmpty(targetMethod)) {
return NOT_FOUND_LINE_NUMBER;
}
final String targetClassText = CLASS_PREFIX.concat(trimmedClassName);
final String targetMethodText = targetMethod.concat(METHOD_SUFFIX);
final File sourceCodeFile = new File(filepath);
try (BufferedReader buff = new BufferedReader(new FileReader(sourceCodeFile))) {
String currentLine;
int foundLineNumber = NOT_FOUND_LINE_NUMBER;
int currentLineNumber = 1;
boolean classFound = false;
while ((currentLine = buff.readLine()) != null && foundLineNumber == NOT_FOUND_LINE_NUMBER) {
if (currentLine.contains(targetClassText)) {
classFound = true;
}
if (classFound && currentLine.contains(targetMethodText)) {
foundLineNumber = currentLineNumber;
}
currentLineNumber += 1;
}
return foundLineNumber;
} catch (final IOException e) {
return NOT_FOUND_LINE_NUMBER;
}
}
public static List readAllLines(final File file) throws IOException {
return java.nio.file.Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy