Skip to content

Commit

Permalink
[ Add, Edit ] added some comments to config controller, refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
anasfik committed Dec 6, 2023
1 parent 7f31c1e commit 6e7e74f
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 59 deletions.
28 changes: 14 additions & 14 deletions lib/src/commands/config_command/sub_commands/create_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ class ConfigCreateCommand extends Command<int> {

@override
Future<int> run() async {
final configFileController = ConfigFile.fromArgResults(argResults!);
final configFileController =
ConfigFileController.fromArgResults(argResults!);

try {
final file = configFileController.configFileRef;
Expand All @@ -51,7 +52,8 @@ class ConfigCreateCommand extends Command<int> {

return await _requestToOverwrite(file, configFileController);
} else {
return await _promptForConfigFileCreation(configFileController);
return await _promptForConfigFileControllerCreation(
configFileController);
}
} catch (e) {
logger.err(e.toString());
Expand All @@ -62,7 +64,7 @@ class ConfigCreateCommand extends Command<int> {

Future<int> _requestToOverwrite(
File file,
ConfigFile configFileController,
ConfigFileController configFileController,
) async {
final confirmOverwrite = logger.confirm('Do you want to overwrite it?');

Expand All @@ -85,8 +87,8 @@ class ConfigCreateCommand extends Command<int> {
}
}

Future<int> _promptForConfigFileCreation(
ConfigFile configFileController,
Future<int> _promptForConfigFileControllerCreation(
ConfigFileController configFileController,
) async {
const examplePath = './locales/en.json';

Expand Down Expand Up @@ -166,14 +168,12 @@ class ConfigCreateCommand extends Command<int> {
);

// Create the config with the given
final config = configFileController.futureConfigToWrite(
config: LangSyncConfig(
outputDir: outputDir,
sourceFile: sourceLocalizationFilePath,
langs: targetLangsList,
instruction: instruction,
),
);
final config = LangSyncConfig(
outputDir: outputDir,
sourceFile: sourceLocalizationFilePath,
langs: targetLangsList,
instruction: instruction,
).toMap();

final creationProgress = logger.customProgress(
'Creating ${configFileController.configFileName} file',
Expand All @@ -186,7 +186,7 @@ class ConfigCreateCommand extends Command<int> {
'${configFileController.configFileName} file is created, updating it with your config...',
);

await configFileController.writeNewConfig(config);
configFileController.writeNewConfig(config);

creationProgress.complete(
'${configFileController.configFileName} file created & updated with your config successfully.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ class ConfigValidateCommand extends Command<int> {

@override
Future<int>? run() async {
final configFiles = ConfigFile.configFilesInCurrentDir.toList();
final configFiles = ConfigFileController.configFilesInCurrentDir.toList();

ConfigFile configFile;
ConfigFileController configFile;

try {
configFile = _controllerFromFile(configFiles: configFiles);
Expand Down Expand Up @@ -77,7 +77,7 @@ class ConfigValidateCommand extends Command<int> {
}
}

ConfigFile _controllerFromFile({
ConfigFileController _controllerFromFile({
required List<FileSystemEntity> configFiles,
}) {
if (configFiles.isEmpty) {
Expand All @@ -99,6 +99,6 @@ class ConfigValidateCommand extends Command<int> {
throw ExitCode.software.code;
}

return ConfigFile.controllerFromFile(configFiles.first);
return ConfigFileController.controllerFromFile(configFiles.first);
}
}
8 changes: 4 additions & 4 deletions lib/src/commands/start_command/start_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ class StartCommand extends Command<int> {
return ExitCode.config.code;
}

ConfigFile configFile;
ConfigFileController configFile;

try {
final configFiles = ConfigFile.configFilesInCurrentDir.toList();
final configFiles = ConfigFileController.configFilesInCurrentDir.toList();

configFile = _controllerFromFile(configFiles: configFiles);
} catch (e) {
Expand Down Expand Up @@ -316,7 +316,7 @@ class StartCommand extends Command<int> {
return completer.future;
}

ConfigFile _controllerFromFile({
ConfigFileController _controllerFromFile({
required List<FileSystemEntity> configFiles,
}) {
if (configFiles.isEmpty) {
Expand All @@ -338,6 +338,6 @@ class StartCommand extends Command<int> {
throw ExitCode.software.code;
}

return ConfigFile.controllerFromFile(configFiles.first);
return ConfigFileController.controllerFromFile(configFiles.first);
}
}
61 changes: 36 additions & 25 deletions lib/src/etc/controllers/config_file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,57 @@ import 'package:meta/meta.dart';

import 'package:langsync/src/etc/controllers/json.dart';
import 'package:langsync/src/etc/controllers/yaml.dart';
import 'package:langsync/src/etc/models/config.dart';

abstract class ConfigFile {
static ConfigFile fromArgResults(ArgResults argResults) {
if (argResults['json'] == true) {
/// Decided and manages the LangSync config file controller.
abstract class ConfigFileController {
/// Created the convenable [ConfigFileController] from the [argResults] of the CLI call.
/// If no [argResults] are provided, the default controller is returned.
static ConfigFileController fromArgResults(ArgResults argResults) {
final isJson = argResults['json'] == true;
final isYaml = argResults['yaml'] == true;

if (isJson) {
return JsonController();
} else if (argResults['yaml'] == true) {
} else if (isYaml) {
return YamlController();
} else {
return defaultController;
}
}

static final Map<String, ConfigFile> _controllers = [
/// The controllers that are supported by LangSync, the goal of this implementation is to make it easy to locate the expected config file name of each and to be able to add more in the future.
static final Map<String, ConfigFileController> _controllers = [
YamlController(),
JsonController(),
].asMap().map(
(_, controller) => MapEntry(controller.configFileName, controller),
);

static Iterable<FileSystemEntity> get configFilesInCurrentDir =>
Directory('.').listSync().where(
(file) {
final fileName = file.fileNameOnly;
/// Returns the existant expected config files of the controllers in the current directory. (the project directory)
static Iterable<FileSystemEntity> get configFilesInCurrentDir {
final fileEntities = Directory('.').listSync();

return _controllers.containsKey(fileName);
},
);
return fileEntities.where(
(file) => _controllers.containsKey(file.fileNameOnly),
);
}

static ConfigFile get defaultController => YamlController();
/// Returns the default controller of LangSync, which is the [YamlController].
/// This is the controller that is used when no controller is specified.
static ConfigFileController get defaultController => YamlController();

/// The config file reference.
File get configFileRef;

// String get configFileExtension => configFileRef.path.split('.').last;

String get configFileName => configFileRef.fileNameOnly;

/// The config file content parsed as a map of dynamic keys and values.
Future<Map<dynamic, dynamic>> parsed();

/// !
@protected
Future<Map<dynamic, dynamic>> parsedConfigFileContent({
Future<Map<dynamic, dynamic>> parsedConfigFileControllerContent({
required Future<Map<dynamic, dynamic>> Function(String fileContentAsString)
loadConfigAsMapCallback,
}) async {
Expand All @@ -60,11 +70,13 @@ abstract class ConfigFile {
return loadConfigAsMapCallback(asString);
}

/// Creates the config file if it does not exist.
Future<File> createConfigFile() {
return configFileRef.create();
}

Future<void> writeToConfigFile(String writableContent) async {
/// Writes the raw [writableContent] string to the config file.
void writeToConfigFileController(String writableContent) {
if (!configFileRef.existsSync()) {
throw Exception('Config file does not exist.');
}
Expand All @@ -75,6 +87,7 @@ abstract class ConfigFile {
);
}

/// Validates the config file fields of LangSync, this is universal and static because it relies on the config file content parsed as a map.
bool validateConfigFields(Map<dynamic, dynamic> parsedConfigAsMap) {
final langsyncConfig = parsedConfigAsMap['langsync'] as Map?;

Expand Down Expand Up @@ -117,12 +130,7 @@ abstract class ConfigFile {
}
}

Map<String, dynamic> futureConfigToWrite({
required LangSyncConfig config,
}) {
return config.toMap();
}

/// Logs the config file fields of LangSync, this is universal and static because it relies on the config file content parsed as a map.
void iterateAndLogConfig(Map<dynamic, dynamic> parsedYaml, Logger logger) {
logger.info('');

Expand All @@ -136,6 +144,7 @@ abstract class ConfigFile {
logger.info('');
}

/// Iterates over the config file fields of LangSync, this is universal and static because it relies on the config file content parsed as a map.
void iterateOverConfig(
Map<dynamic, dynamic> config, {
required void Function(MapEntry<dynamic, dynamic> configEntry) callback,
Expand All @@ -145,9 +154,11 @@ abstract class ConfigFile {
}
}

Future<void> writeNewConfig(Map<String, dynamic> config);
/// Writes the new config file to the config file controller.
void writeNewConfig(Map<String, dynamic> config);

static ConfigFile controllerFromFile(FileSystemEntity file) {
/// Returns the config file controller from the [file].
static ConfigFileController controllerFromFile(FileSystemEntity file) {
final fileName = file.fileNameOnly;

return _controllers[fileName]!;
Expand Down
9 changes: 5 additions & 4 deletions lib/src/etc/controllers/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@ import 'dart:io';
import 'package:langsync/src/etc/controllers/config_file.dart';
import 'package:langsync/src/etc/extensions.dart';

class JsonController extends ConfigFile {
/// A JSON config file controller.
class JsonController extends ConfigFileController {
@override
File get configFileRef => File('./langsync.json');

@override
Future<Map<dynamic, dynamic>> parsed() {
return super.parsedConfigFileContent(
return super.parsedConfigFileControllerContent(
loadConfigAsMapCallback: (fileContentAsString) async {
return await jsonDecode(fileContentAsString) as Map<dynamic, dynamic>;
},
);
}

@override
Future<void> writeNewConfig(Map<String, dynamic> config) {
return super.writeToConfigFile(
void writeNewConfig(Map<String, dynamic> config) {
return super.writeToConfigFileController(
{'langsync': config}.toPrettyJson(),
);
}
Expand Down
16 changes: 8 additions & 8 deletions lib/src/etc/controllers/yaml.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,42 @@ import 'package:langsync/src/etc/controllers/config_file.dart';
import 'package:langsync/src/etc/extensions.dart';
import 'package:yaml/yaml.dart' as yaml;

class YamlController extends ConfigFile {
class YamlController extends ConfigFileController {
@override
File get configFileRef => File('./langsync.yaml');

@override
Future<Map<dynamic, dynamic>> parsed() async {
return super.parsedConfigFileContent(
return super.parsedConfigFileControllerContent(
loadConfigAsMapCallback: (fileContentAsString) async {
return await yaml.loadYaml(fileContentAsString) as Map;
},
);
}

@override
Future<void> writeNewConfig(Map<String, dynamic> config) async {
await super.writeToConfigFile('langsync:\n');
void writeNewConfig(Map<String, dynamic> config) async {
super.writeToConfigFileController('langsync:\n');

await _iterateAndWriteToConfigFile(config);
await _iterateAndWriteToConfigFileController(config);
}

Future<void> _iterateAndWriteToConfigFile(
Future<void> _iterateAndWriteToConfigFileController(
Map<dynamic, dynamic> config,
) async {
super.iterateOverConfig(
config,
callback: (entry) async {
if (entry.value is String) {
if ((entry.value as String).isPathToFileOrFolder()) {
await super.writeToConfigFile(
super.writeToConfigFileController(
"\n ${entry.key}: '${entry.value}' \n",
);
return;
}
}

await super.writeToConfigFile(
super.writeToConfigFileController(
'\n ${entry.key}: ${entry.value} \n',
);
},
Expand Down

0 comments on commit 6e7e74f

Please sign in to comment.