Skip to content

Commit

Permalink
[ Add ] Added support for json configuration in addition of the yaml …
Browse files Browse the repository at this point in the history
…configuration, with the default one being yaml, the user can specify it with the `--json`, `--yaml`...
  • Loading branch information
anasfik committed Oct 17, 2023
1 parent 9b84ba2 commit 616b8e8
Show file tree
Hide file tree
Showing 12 changed files with 404 additions and 181 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@

- Bug Fixes.
- Appliance of new Stream API, which allow for better performance, faster updates and more stability.

## 0.9.42

- Added support for json configuration in addition of the yaml configuration, with the default one being yaml, the user can specify it with the `--json`, `--yaml`...
Binary file modified bin/langsync.exe
Binary file not shown.
113 changes: 73 additions & 40 deletions lib/src/commands/config_command/sub_commands/create_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:langsync/src/etc/controllers/config_file.dart';
import 'package:langsync/src/etc/controllers/json.dart';
import 'package:langsync/src/etc/controllers/yaml.dart';
import 'package:langsync/src/etc/extensions.dart';
import 'package:langsync/src/etc/networking/client.dart';
Expand All @@ -10,28 +12,45 @@ import 'package:mason_logger/mason_logger.dart';
class ConfigCreateCommand extends Command<int> {
ConfigCreateCommand({
required this.logger,
});
}) {
argParser
..addFlag(
'json',
help: 'Create a JSON file for the configuration (langsync.json)',
negatable: false,
)
..addFlag(
'yaml',
help:
'Create a YAML file for the configuration (langsync.yaml or langsync.yml)',
negatable: false,
);
}

final Logger logger;

@override
String get description =>
'Creates a new langsync.yaml file in the current directory.';
'Creates a new LangSync configuration file in the current directory, you can also specify the type of the configuration file (JSON, YAML)';

@override
String get name => 'create';

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

try {
final file = File('./langsync.yaml');
final file = configFileController.configFileRef;

if (file.existsSync()) {
logger.info('langsync.yaml already exists in the current directory.');
logger.info(
'${configFileController.configFileName} already exists in the current directory.',
);

return await _requestToOverwrite(file);
return await _requestToOverwrite(file, configFileController);
} else {
return await _promptForConfigFileCreation();
return await _promptForConfigFileCreation(configFileController);
}
} catch (e) {
logger.err(e.toString());
Expand All @@ -40,17 +59,19 @@ class ConfigCreateCommand extends Command<int> {
}
}

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

if (confirmOverwrite) {
final deleteLogger =
logger.customProgress('Deleting the existant langsync.yaml file');
final deleteLogger = logger.customProgress(
'Deleting the existent ${configFileController.configFileName} file',
);

await file.delete();

deleteLogger.complete(
'The already existing langsync.yaml file is deleted successfully',
'The already existing ${configFileController.configFileName} file is deleted successfully',
);

return run();
Expand All @@ -61,12 +82,22 @@ class ConfigCreateCommand extends Command<int> {
}
}

Future<int> _promptForConfigFileCreation() async {
final sourceLocalizationFilePath = logger.prompt(
'Enter the path to the source localization file (e.g. ./locales/en.json): ',
Future<int> _promptForConfigFileCreation(
ConfigFile configFileController,
) async {
const examplePath = './locales/en.json';

var sourceLocalizationFilePath = logger.prompt(
'Enter the path to the source localization file (e.g. $examplePath): ',
);

final sourceFile = File(sourceLocalizationFilePath);
sourceLocalizationFilePath = sourceLocalizationFilePath.isEmpty
? examplePath
: sourceLocalizationFilePath;

final sourceFile = File(
sourceLocalizationFilePath,
);

if (!sourceFile.existsSync()) {
logger
Expand All @@ -78,10 +109,14 @@ class ConfigCreateCommand extends Command<int> {
return ExitCode.software.code;
}

final outputDir = logger.prompt(
'Enter the path to the output directory (e.g. ./locales): ',
const defaultOutpitDir = './locales';

var outputDir = logger.prompt(
'Enter the path to the output directory (e.g. $defaultOutpitDir): ',
);

outputDir = outputDir.isEmpty ? defaultOutpitDir : outputDir;

final outputDirectory = Directory(outputDir);

if (!outputDirectory.existsSync()) {
Expand All @@ -107,46 +142,43 @@ class ConfigCreateCommand extends Command<int> {
}
}

final targetLangs = logger.prompt(
'Enter the target languages (e.g. italian,spanish,german): ',
const defaultTarget = 'zh, ru, ar, fr';

var targetLangs = logger.prompt(
'Enter the target languages (e.g. $defaultTarget): ',
);

targetLangs = targetLangs.isEmpty ? defaultTarget : targetLangs;

final targetLangsList = targetLangs.trim().split(',').map((e) => e.trim());

if (targetLangsList.isEmpty) {
logger.err('No target languages were provided.');
if (targetLangsList.any((e) => e.length < 2)) {
logger.err('Some of the target languages are invalid.');

return ExitCode.software.code;
} else {
if (targetLangsList.any((e) => e.length < 2)) {
logger.err('Some of the target languages are invalid.');

return ExitCode.software.code;
}
}

final config = YamlController.futureYamlFormatFrom(
final config = configFileController.futureConfigToWrite(
outputDir: outputDir,
sourceLocalizationFilePath: sourceLocalizationFilePath,
targetLangsList: targetLangsList,
);

final creationProgress =
logger.customProgress('Creating langsync.yaml file');
final creationProgress = logger.customProgress(
'Creating ${configFileController.configFileName} file',
);

try {
await YamlController.createConfigFile();
await configFileController.createConfigFile();

creationProgress.update(
'langsync.yaml file is created, updating it with your config...',
'${configFileController.configFileName} file is created, updating it with your config...',
);

await YamlController.writeToConfigFile('langsync:\n');

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

creationProgress.complete(
'langsync.yaml file created & updated with your config successfully.',
'${configFileController.configFileName} file created & updated with your config successfully.',
);

return ExitCode.success.code;
Expand All @@ -155,7 +187,7 @@ class ConfigCreateCommand extends Command<int> {
error: e,
progress: creationProgress,
update:
'Something went wrong while creating the langsync.yaml file, please try again.',
'Something went wrong while creating the ${configFileController.configFileName} file, please try again.',
);

try {
Expand All @@ -165,10 +197,11 @@ class ConfigCreateCommand extends Command<int> {
commandName: name,
);

logger.info('\n');
logger.warn(
'This error has been reported to the LangSync team, we will definitely look into it!',
);
logger
..info('\n')
..warn(
'This error has been reported to the LangSync team, we will definitely look into it!',
);
} catch (e) {}

return ExitCode.software.code;
Expand Down
67 changes: 49 additions & 18 deletions lib/src/commands/config_command/sub_commands/validate_command.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:langsync/src/etc/controllers/yaml.dart';
import 'package:langsync/src/etc/controllers/config_file.dart';
import 'package:langsync/src/etc/extensions.dart';
import 'package:mason_logger/mason_logger.dart';

Expand All @@ -20,48 +22,52 @@ class ConfigValidateCommand extends Command<int> {

@override
Future<int>? run() async {
if (!YamlController.configFileRef.existsSync()) {
logger
..info('There is no langsync.yaml file in the current directory.')
..info('Run `langsync config create` to create one.')
..docsInfo(path: '/cli-usage/configure');
final configFiles = ConfigFile.configFilesInCurrentDir.toList();

ConfigFile configFile;

return ExitCode.success.code;
try {
configFile = _controllerFromFile(configFiles: configFiles);
} catch (e) {
return e as int;
}

final validationProgress =
logger.customProgress('Validating the existent langsync.yaml file');
final validationProgress = logger.customProgress(
'Validating the existent ${configFile.configFileName} file',
);

final yamlMap = await YamlController.parsedYaml;
final configMap = await configFile.parsed();

final langsyncConfig = yamlMap['langsync'];
final langsyncConfig = configMap['langsync'];

if (langsyncConfig == null) {
validationProgress.complete(
'langsync.yaml file is missing a `langsync` key.',
'${configFile.configFileName} file is missing a `langsync` key.',
);

return ExitCode.software.code;
} else {
validationProgress.update('Parsing the configuration file');

final parsedYaml = await YamlController.parsedYaml;
final parsedLangsyncMap = await configFile.parsed();

validationProgress.update('Validating the configuration file');

final isValid = YamlController.validateConfigFields(parsedYaml);
final isValid = configFile.validateConfigFields(parsedLangsyncMap);

validationProgress.complete('Validation task completed.');

if (isValid) {
YamlController.iterateAndLogConfig(parsedYaml, logger);
logger.info('langsync.yaml file is valid.');
configFile.iterateAndLogConfig(parsedLangsyncMap, logger);

logger.info('${configFile.configFileName} file is valid.');
return ExitCode.success.code;
} else {
logger
..info('langsync.yaml file is invalid.')
..info('${configFile.configFileName} file is invalid.')
..info(
'''
Please check your langsync.yaml file, or run `langsync config create` to create a new one.
Please check your ${configFile.configFileName} file, or run `langsync config create` to create a new one.
''',
)
..docsInfo(path: '/cli-usage/configure');
Expand All @@ -70,4 +76,29 @@ class ConfigValidateCommand extends Command<int> {
}
}
}

ConfigFile _controllerFromFile({
required List<FileSystemEntity> configFiles,
}) {
if (configFiles.isEmpty) {
logger
..info(
'There is no LangSync configuration file in the current directory.',
)
..info('Run `langsync config create` to create one.')
..docsInfo(path: '/cli-usage/configure');

throw ExitCode.software.code;
}

if (configFiles.length > 1) {
logger.info(
'There are multiple LangSync configuration files in the current directory, please remove the extra ones and try again.',
);

throw ExitCode.software.code;
}

return ConfigFile.controllerFromFile(configFiles.first);
}
}
Loading

0 comments on commit 616b8e8

Please sign in to comment.