process function

void process(
  1. String srcPath,
  2. String outPath,
  3. List<String> filenames,
  4. bool isTest,
)

Implementation

void process(String srcPath, String outPath, List<String> filenames, bool isTest) {
	final Directory srcDir = Directory(srcPath);
	final Directory outDir = Directory(outPath);
	final List<FileSystemEntity> files = <FileSystemEntity>[];
	final RegExp reJson = RegExp(r'\.json$');
	final RegExp reName = RegExp(r'.+[/\\](.+?)\.json$');
	try {
		if (!srcDir.existsSync()) throw Exception('Path not found: $srcPath');
		if (!outDir.existsSync()) outDir.createSync(recursive: true);
		files.addAll(srcDir.listSync());
	}
	catch (err) {
		throw Exception('Unable to process files: $err');
	}

	/// Filter file system entities, leave only manifest files to process
	files.removeWhere((FileSystemEntity file) {
		if (!reJson.hasMatch(file.path)) return true;
		if (filenames.isNotEmpty) {
			final String filename = reName.firstMatch(file.path)!.group(1)! + '.json';
			return !filenames.contains(filename);
		}
		else return false;
	});
	for (final FileSystemEntity file in files) {
		final String filename = reName.firstMatch(file.path)!.group(1)! + '.json';
		filenames.remove(filename);
	}
	if (files.isEmpty) throw Exception('No manifest files found');
	if (filenames.isNotEmpty) throw Exception('File not found: ${filenames.first}');

	final Map<String, Container> containers = <String, Container>{};

	for (final FileSystemEntity file in files) {
		final String filename = reName.firstMatch(file.path)!.group(1)!;

		/// Try to get file contents as potential JSON string
		String json;
		try {
			json = File(file.path).readAsStringSync();
		}
		catch (err) {
			throw Exception('Unable to open manifest file: $err');
		}

		/// Try to parse JSON
		const JsonDecoder decoder = JsonDecoder();
		late final Map<String, dynamic> manifest;
		try {
			manifest = decoder.convert(json) as Map<String, dynamic>;
		}
		catch (err) {
			throw Exception('Unable to parse $filename.json: $err');
		}

		/// Create container with nodes from parsed data
		containers[filename] = Container(filename, manifest, containers);
	}

	final Map<String, List<String>> codePerFile = <String, List<String>>{};

	/// Process nodes and get resulting code strings
	for (final Container container in containers.values) {
		codePerFile[container.filename] ??= <String>[];
		codePerFile[container.filename]!.addAll(container.output(containers));
	}

	/// Output resulting code
	for (final String filename in codePerFile.keys) {
		if (!isTest) {
			File('$outPath/$filename.generated.dart').writeAsStringSync(formatCode(codePerFile[filename]!).join('\n'));
		}
		else {
			print('$filename.generated.dart: ~${formatCode(codePerFile[filename]!).join('\n').length} bytes');
		}
	}

	print('$GREEN${files.length} file${ files.length > 1 ? 's are' : ' is'} successfully processed$RESET');
}