Skip to content

Commit

Permalink
[JS] generateMainResourceFile
Browse files Browse the repository at this point in the history
  • Loading branch information
JabX committed Feb 16, 2024
1 parent 3608c0d commit d723e5f
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 9 deletions.
44 changes: 40 additions & 4 deletions TopModel.Generator.Core/TranslationGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public TranslationGeneratorBase(ILogger<TranslationGeneratorBase<T>> logger, Tra

return properties.SelectMany(p => GetResourceFileNames(p, tag))
.Concat(properties.SelectMany(p => GetCommentResourceFileNames(p, tag)))
.Concat(GetMainResourceFileNames(tag))
.Select(p => p.FilePath);
})
.Distinct();
Expand All @@ -33,32 +34,60 @@ public TranslationGeneratorBase(ILogger<TranslationGeneratorBase<T>> logger, Tra
return null;
}

protected virtual string? GetMainResourceFilePath(string tag, string lang)
{
return null;
}

protected abstract string? GetResourceFilePath(IFieldProperty property, string tag, string lang);

protected virtual void HandleCommentResourceFile(string filePath, string lang, IEnumerable<IFieldProperty> properties)
{
}

protected virtual void HandleMainResourceFile(string mainFilePath, IEnumerable<(string ModuleFilePath, string ModuleName)> modules)
{
}

protected override void HandleFiles(IEnumerable<ModelFile> files)
{
var modules = new List<(string MainFilePath, string ModuleFilePath, string ModuleName)>();

foreach (var resources in Classes
.SelectMany(classe => Config.Tags.Intersect(classe.Tags)
.SelectMany(tag => classe.Properties.OfType<IFieldProperty>()
.SelectMany(p => GetResourceFileNames(p, tag)
.Select(f => (key: (f.FilePath, f.Lang), p)))))
.Select(f => (key: (MainFilePath: GetMainResourceFilePath(tag, f.Lang), ModuleFilePath: f.FilePath, f.Lang), p)))))
.GroupBy(f => f.key))
{
HandleResourceFile(resources.Key.FilePath, resources.Key.Lang, resources.Select(r => r.p.ResourceProperty).Distinct());
var properties = resources.Select(r => r.p.ResourceProperty).Distinct();
HandleResourceFile(resources.Key.ModuleFilePath, resources.Key.Lang, properties);

if (resources.Key.MainFilePath != null)
{
modules.Add((resources.Key.MainFilePath, resources.Key.ModuleFilePath, properties.First().Parent.Namespace.RootModule));
}
}

foreach (var resources in Classes
.SelectMany(classe => Config.Tags.Intersect(classe.Tags)
.SelectMany(tag => classe.Properties.OfType<IFieldProperty>()
.SelectMany(p => GetCommentResourceFileNames(p, tag)
.Select(f => (key: (f.FilePath, f.Lang), p)))))
.Select(f => (key: (MainFilePath: GetMainResourceFilePath(tag, f.Lang), ModuleFilePath: f.FilePath, f.Lang), p)))))
.GroupBy(f => f.key))
{
HandleCommentResourceFile(resources.Key.FilePath, resources.Key.Lang, resources.Select(r => r.p.CommentResourceProperty).Distinct());
var properties = resources.Select(r => r.p.CommentResourceProperty).Distinct();
HandleCommentResourceFile(resources.Key.ModuleFilePath, resources.Key.Lang, properties);

if (resources.Key.MainFilePath != null)
{
modules.Add((resources.Key.MainFilePath, resources.Key.ModuleFilePath, $"{properties.First().Parent.Namespace.RootModule}Comments"));
}
}

foreach (var g in modules.GroupBy(m => m.MainFilePath))
{
HandleMainResourceFile(g.Key, g.Select(l => (l.ModuleFilePath, l.ModuleName)).OrderBy(m => m.ModuleFilePath));
}
}

Expand All @@ -71,6 +100,13 @@ protected override void HandleFiles(IEnumerable<ModelFile> files)
.Where(g => g.file != null);
}

private IEnumerable<(string Lang, string FilePath)> GetMainResourceFileNames(string tag)
{
return _translationStore.Translations
.Select(lang => (lang: lang.Key, file: GetMainResourceFilePath(tag, lang.Key)!))
.Where(g => g.file != null);
}

private IEnumerable<(string Lang, string FilePath)> GetResourceFileNames(IFieldProperty property, string tag)
{
return _translationStore.Translations
Expand Down
23 changes: 19 additions & 4 deletions TopModel.Generator.Javascript/JavascriptConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ public class JavascriptConfig : GeneratorConfigBase
/// </summary>
public bool GenerateComments { get; set; }

/// <summary>
/// Génère un fichier 'index.ts' qui importe et réexporte tous les fichiers de resources générés par langue. Uniquement compatible avec `resourceMode: js`.
/// </summary>
public bool GenerateMainResourceFiles { get; set; }

public override string[] PropertiesWithModuleVariableSupport => new[]
{
nameof(ApiClientFilePath)
Expand Down Expand Up @@ -111,7 +116,7 @@ public string GetCommentResourcesFilePath(Namespace ns, string tag, string lang)
public IEnumerable<(string Import, string Path)> GetDomainImportPaths(string fileName, IProperty prop, string tag)
{
return GetDomainImports(prop, tag)
.Select(import => (Import: import.Split("/").Last(), Path: GetRelativePath(import[..import.LastIndexOf("/")], fileName)));
.Select(import => (Import: import.Split("/").Last(), Path: GetRelativePath(import[..import.LastIndexOf('/')], fileName)));
}

public List<(string Import, string Path)> GetEndpointImports(string fileName, IEnumerable<Endpoint> endpoints, string tag, IEnumerable<Class> availableClasses)
Expand Down Expand Up @@ -174,22 +179,32 @@ public string GetEndpointsFileName(ModelFile file, string tag)

var path = Path.GetRelativePath(string.Join('/', source.Split('/').SkipLast(1)), target)[..^3].Replace("\\", "/");

if (!path.StartsWith("."))
if (!path.StartsWith('.'))
{
path = $"./{path}";
}

return path;
}

public string GetMainResourceFilePath(string tag, string lang)
{
return Path.Combine(
OutputDirectory,
ResolveVariables(ResourceRootPath!, tag),
lang,
"index.ts")
.Replace("\\", "/");
}

public string GetReferencesFileName(Namespace ns, string tag)
{
return Path.Combine(OutputDirectory, ResolveVariables(ModelRootPath!, tag), ns.ModulePathKebab, "references.ts").Replace("\\", "/");
}

public string GetRelativePath(string path, string fileName)
{
return !path.StartsWith(".")
return !path.StartsWith('.')
? path
: Path.GetRelativePath(string.Join('/', fileName.Split('/').SkipLast(1)), Path.Combine(OutputDirectory, path)).Replace("\\", "/");
}
Expand All @@ -207,7 +222,7 @@ public string GetResourcesFilePath(Namespace ns, string tag, string lang)
public IEnumerable<(string Import, string Path)> GetValueImportPaths(string fileName, IFieldProperty prop, string? value = null)
{
return GetValueImports(prop, value)
.Select(import => (Import: import.Split("/").Last(), Path: GetRelativePath(import[..import.LastIndexOf("/")], fileName)));
.Select(import => (Import: import.Split("/").Last(), Path: GetRelativePath(import[..import.LastIndexOf('/')], fileName)));
}

public bool IsListComposition(IProperty property)
Expand Down
31 changes: 30 additions & 1 deletion TopModel.Generator.Javascript/JavascriptResourceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ public JavascriptResourceGenerator(ILogger<JavascriptResourceGenerator> logger,
return Config.GetCommentResourcesFilePath(property.Parent.Namespace, tag, _modelConfig.I18n.DefaultLang);
}

protected override string? GetMainResourceFilePath(string tag, string lang)
{
if (!Config.GenerateMainResourceFiles || Config.ResourceMode != ResourceMode.JS)
{
return null;
}

return Config.GetMainResourceFilePath(tag, lang);
}

protected override string GetResourceFilePath(IFieldProperty property, string tag, string lang)
{
return Config.GetResourcesFilePath(property.Parent.Namespace, tag, lang);
Expand All @@ -51,7 +61,7 @@ protected override void HandleCommentResourceFile(string filePath, string lang,
}
else
{
fw.WriteLine($"export const {module.ToCamelCase()} = {{");
fw.WriteLine($"export const {module.ToCamelCase()}Comments = {{");
}

WriteSubModule(fw, _modelConfig.I18n.DefaultLang, properties, true, 1);
Expand All @@ -66,6 +76,25 @@ protected override void HandleCommentResourceFile(string filePath, string lang,
}
}

protected override void HandleMainResourceFile(string mainFilePath, IEnumerable<(string ModuleFilePath, string ModuleName)> modules)
{
using var fw = new FileWriter(mainFilePath, _logger, encoderShouldEmitUTF8Identifier: false) { EnableHeader = true };

foreach (var (moduleFilePath, moduleName) in modules)
{
fw.WriteLine($"import {{{moduleName.ToCamelCase()}}} from \"./{Path.GetRelativePath(Path.GetDirectoryName(mainFilePath)!, moduleFilePath).Replace("\\", "/").Replace(".ts", string.Empty)}\";");
}

fw.WriteLine();
fw.WriteLine($"export const all = {{{string.Join(", ", modules.Where(m => !m.ModuleFilePath.EndsWith(".comments.ts")).Select(m => m.ModuleName.ToCamelCase()))}}};");

var comments = modules.Where(m => m.ModuleFilePath.EndsWith(".comments.ts")).Select(m => m.ModuleName.ToCamelCase());
if (comments.Any())
{
fw.WriteLine($"export const allComments = {{{string.Join(", ", comments)}}};");
}
}

protected override void HandleResourceFile(string filePath, string lang, IEnumerable<IFieldProperty> properties)
{
using var fw = new FileWriter(filePath, _logger, encoderShouldEmitUTF8Identifier: false) { EnableHeader = Config.ResourceMode == ResourceMode.JS };
Expand Down
4 changes: 4 additions & 0 deletions TopModel.Generator.Javascript/javascript.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@
"type": "boolean",
"description": "Ajoute les commentaires dans les entités JS générées."
},
"generateMainResourceFiles": {
"type": "boolean",
"description": "Génère un fichier 'index.ts' qui importe et réexporte tous les fichiers de resources générés par langue. Uniquement compatible avec `resourceMode: js`."
},
"referenceMode": {
"type": "string",
"description": "Mode de génération des listes de références (définitions ou valeurs).",
Expand Down

0 comments on commit d723e5f

Please sign in to comment.