Here is a Dart script that recursively searches through Dart files in a directory and its subdirectories, extracts strings (literals), the file path, line containing the string, and the string itself.
import 'dart:io';
import 'dart:convert';
void main(List args) {
if (args.isEmpty) {
print('Usage: dart find_data_models.dart ');
return;
}
final directory = Directory(args[0]);
if (!directory.existsSync()) {
print('Directory does not exist');
return;
}
searchDirectory(directory);
}
void searchDirectory(Directory directory) {
final files = directory.listSync(recursive: true);
for (var file in files) {
if (file is File && file.path.endsWith('.dart')) {
extractDataModels(file);
}
}
}
void extractDataModels(File file) {
final lines = file.readAsLinesSync();
final dataModelPattern = RegExp(r'class\s+(\w+)\s*\{');
final propertyPattern = RegExp(r'\s*(final|var|late)?\s*(\w+)\s+(\w+);');
for (var i = 0; i < lines.length; i++) {
final line = lines[i];
final classMatch = dataModelPattern.firstMatch(line);
if (classMatch != null) {
final className = classMatch.group(1);
print('Data Model: $className found in ${file.path} at line ${i + 1}');
print(line.trim());
for (var j = i + 1; j < lines.length; j++) {
final nextLine = lines[j];
final propertyMatch = propertyPattern.firstMatch(nextLine);
if (propertyMatch != null) {
print('Property found in ${file.path} at line ${j + 1}');
print(nextLine.trim());
}
if (nextLine.contains('}')) {
break; // End of class
}
}
print('');
}
}
} Instructions: Save this script as find_data_models.dart. Open a terminal or command prompt. Navigate to the directory containing find_data_models.dart. Run the script with the target directory as an argument:
dart find_data_models.dart /path/to/your/dart/project
Script Explanation
- the script takes a directory path as a command-line argument.
- It checks if the directory exists and then lists all files in the directory and subdirectories.
- For each Dart file, it reads the lines and searches for string literals using a regular expression.
- Upon finding a string literal, it prints the file path, the line number containing the string, and the string itself.
This script should help you extract string literals from Dart files within a specified directory and its subdirectories. You could:
- modify yourself the regex part and checks there
- create your own data model and return it as list from the search.
This article was generated from my ChatGPT wrapper. https://programtom.com/dev/product/gpt-spring-boot-micro-service/
