A collection of helpful source generators.
- ConstantFromJsonGenerator.cs: A source generator that creates a constant from a JSON file.
For general details about and on using the Helpful Libraries see the root Readme.
-
Add a JSON file to your project.
-
Set the
Build Action
of the JSON file toAdditionalFiles
for example:<ItemGroup> <AdditionalFiles Include="package.json" /> </ItemGroup>
-
Add reference to both the Source Generator and the Attributes project (this adds the marker attribute 'ConstantFromJson') and make sure to include the project as analyzer:
<ProjectReference Include="..\Lombiq.HelpfulLibraries.Attributes\Lombiq.HelpfulLibraries.Attributes.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" /> <ProjectReference Include="..\Lombiq.HelpfulLibraries.SourceGenerators\Lombiq.HelpfulLibraries.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
-
In the samples you can also see the snippet below, while not strictly necessary for the source generator to function, it suppresses a warning that happens in Visual Studio when first cloning the project. If you do decide to include this part make sure you update the relative paths to the correct location of the projects.
<PropertyGroup> <SourceGeneratorLocation>$(SolutionDir)src\Libraries\Lombiq.HelpfulLibraries\Lombiq.HelpfulLibraries.SourceGenerators\bin\Debug\netstandard2.0\Lombiq.HelpfulLibraries.SourceGenerators.dll</SourceGeneratorLocation> <SourceGeneratorLocation Condition=" '$(Configuration)' != 'Debug' ">$(SolutionDir)src\Libraries\Lombiq.HelpfulLibraries\Lombiq.HelpfulLibraries.SourceGenerators\bin\Release\netstandard2.0\Lombiq.HelpfulLibraries.SourceGenerators.dll</SourceGeneratorLocation> </PropertyGroup> <Target Name="CustomBeforeCompile" BeforeTargets="Compile"> <MSBuild Condition="!Exists('$(SourceGeneratorLocation)')" Projects="..\Lombiq.HelpfulLibraries.SourceGenerators\Lombiq.HelpfulLibraries.SourceGenerators.csproj" /> </Target>
-
Wherever you want to use the JSON file, make sure to use a
partial class
and add theConstantFromJsonGenerator
attribute to it. Where the first parameter is the name of the constant and the second parameter is the path to the JSON file, the last parameter is the name or 'key' for the value we are looking for.[ConstantFromJson("GulpVersion", "package.json", "gulp")] public partial class YourClass { }
-
Run a build and the constant will be generated.
-
Use the constant in your code, full example:
using System; using Generators; namespace Lombiq.HelpfulLibraries.SourceGenerators.Sample; [ConstantFromJson("GulpUglifyVersion", "package.json", "gulp-uglify")] [ConstantFromJson("GulpVersion", "package.json", "gulp")] public partial class Examples { // Show usage of the generated constants public void LogVersions() { Console.WriteLine(GulpUglifyVersion); Console.WriteLine(GulpVersion); } }