Last active
April 9, 2024 09:29
-
-
Save eEQK/a4abfbd1049d5ebf3cec96b39fa41a58 to your computer and use it in GitHub Desktop.
automatically create and wire part/part of in dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dart run main.dart -f foo_form.dart -f foo_state.dart --link-to foo_screen.dart | |
import 'dart:io'; | |
import 'package:args/args.dart'; | |
const linkToOption = 'link-to'; | |
void main(List<String> arguments) async { | |
final parser = ArgParser() | |
..addMultiOption('file', abbr: 'f', help: 'File names to create') | |
..addOption(linkToOption, abbr: 'l', help: 'Filename to link parts to'); | |
final results = parser.parse(arguments); | |
final fileNames = results['file'] as List<String>; | |
final linkTo = results[linkToOption] as String?; | |
if (fileNames.isEmpty || linkTo == null) { | |
print(parser.usage); | |
exit(1); | |
} | |
final linkToFile = File(linkTo); | |
if (!await linkToFile.exists()) { | |
stderr.writeln('File "$linkTo" does not exist, cannot modify.'); | |
exit(1); | |
} | |
final originalContent = await linkToFile.readAsString(); | |
// Build the updated content with part directives | |
final lines = originalContent.split('\n'); | |
final lastImportLine = | |
lines.lastIndexWhere((line) => line.startsWith('import')); | |
final partStart = lastImportLine == -1 ? 0 : lastImportLine + 1; | |
for (final fileName in fileNames.reversed) { | |
lines.insert(partStart, 'part \'$fileName\';'); | |
} | |
if (fileNames.isNotEmpty) { | |
lines.insert(partStart, ''); | |
} | |
await linkToFile.writeAsString(lines.join('\n')); | |
// Create new files as before | |
for (final fileName in fileNames) { | |
final file = File(fileName); | |
if (await file.exists()) { | |
stderr.writeln('File "$fileName" already exists, skipping.'); | |
continue; | |
} | |
final content = ''' | |
part of '$linkTo'; | |
'''; | |
await file.writeAsString(content); | |
print('Created file: $fileName'); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment