Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience extensions to TextTransformationExtensions #2375

Closed
gitfool opened this issue Dec 4, 2018 · 2 comments
Closed

Add convenience extensions to TextTransformationExtensions #2375

gitfool opened this issue Dec 4, 2018 · 2 comments

Comments

@gitfool
Copy link
Contributor

gitfool commented Dec 4, 2018

I would like to add convenience extensions to TextTransformationExtension:

Support for dictionaries:

public static TextTransformation<TTemplate> WithTokens<TTemplate>(
    this TextTransformation<TTemplate> transformation, IDictionary<string, object> tokens)
    where TTemplate : class, ITextTransformationTemplate
{
    if (transformation != null && tokens != null)
    {
        foreach (var token in tokens)
        {
            if (token.Value != null) // leave placeholder for tokens without a value
            {
                transformation.Template.Register(token.Key, token.Value);
            }
        }
    }
    return transformation;
}

Support for shallow object properties, with optional key prefix, that feeds the first extension method:

public static Dictionary<string, object> ToTokens(this object value, string prefix = null, BindingFlags? bindingAttr = null)
{
    return value?.GetType()
        .GetProperties(bindingAttr ?? BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)
        .ToDictionary(property => string.Concat(prefix, property.Name), property => property.GetValue(value));
}

Thoughts? Happy to submit a PR!

@gitfool
Copy link
Contributor Author

gitfool commented Dec 7, 2018

Here's an example of how to use the ToTokens convenience extension:

Task("StageManifest")
    .Does(() =>
{
    TransformTextFile(Build.Files.Manifest, "{{", "}}")
        .WithTokens(Build.Version.ToTokens("Version."))
        .Save(Build.Files.ArtifactsManifest);
});

where the manifest contains placeholders for Version properties (of type GitVersion):

---
name: Test
version:
    semantic_version: {{ Version.FullSemVer }}
    assembly_version: {{ Version.AssemblySemVer }}
    assembly_file_version: {{ Version.AssemblySemFileVer }}
    informational_version: {{ Version.InformationalVersion }}
...

@gitfool
Copy link
Contributor Author

gitfool commented Mar 21, 2019

I use a much more elaborate ToTokens extension now... Cake.Dungeon/scripts/extensions.cake#L9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant