generate function
Generates boilerplate code that makes it easier to access config variables in dart code.
Implementation
Future generate(List<String> args) async {
// Lists the files in the flconf directory
final confDir = Directory(path.join(Directory.current.path, 'flconf'));
if (!await confDir.exists()) {
logError(
'flconf directory not found. Please run flconf init to create it.');
exit(1);
}
final confFiles = confDir.listSync().map((f) => f.path).toList();
/// Starts the process to check flutter version
final result = await Process.run('flutter', ['--version']);
if ((result.stderr ?? '').isNotEmpty) {
logError('Error running flutter --version: ${result.stderr}');
exit(1);
}
/// Checks that the version is at least 2.0.0
final flutterVersion =
result.stdout.toString().split(' ')[1].split('.').join();
if (int.parse(flutterVersion) < 220) {
/// Flutter versions under 2.2.0 are not supported by flconf.
logError('Flutter version 2.2.0 or higher is required.');
exit(1);
}
// These will store the raw AND formatted names of the files/variables.
// Name formatting removes whitespaces/special characters and makes the names camelCase.
final confFileNames = <String, String>{};
final variables = <String, String>{};
final defaults = <String, dynamic>{};
// Iterates over the files in the flconf directory and collects the file names and variables
await Future.wait(
confFiles.map(
(fileName) async {
final confFile = File(fileName);
// Parses the file name and sets the filename variables
final name = confFile.path.split('/').last.split('.').first;
confFileNames[formatCamelCase(name)] = name;
// Parses the variables and sets the variables
final confString = await confFile.readAsString();
final confMap = json.decode(confString) as Map;
confMap.forEach((key, value) {
if (!validateVariableName(key)) {
logError(
'Variable name "$key" is not valid. Variable names must be alphanumeric (with underscores as spaces), capslock and it cannot start with a number.');
exit(1);
}
if (name == 'defaults') {
defaults['FLCONF_' + key] = value;
}
variables[formatCamelCase(key)] = 'FLCONF_' + key;
});
},
),
);
if (defaults.isEmpty) {
logError(
'No defaults file found. Please create a file named "defaults.json" in the flconf directory and apply your variables default values there.');
exit(1);
}
confFileNames.remove('defaults');
await Future.wait(
[
_generateDartBoilerplate(
confFileNames: confFileNames, variables: variables),
_generateAndroidBoilerplate(variables: variables, defaults: defaults),
_generateIOSBoilerplate(variables: variables, defaults: defaults),
],
);
}