diff --git a/src/StrawberryShake/CodeGeneration/StrawberryShake.CodeGeneration.sln b/src/StrawberryShake/CodeGeneration/StrawberryShake.CodeGeneration.sln index b9ac8be414f..675193255f9 100644 --- a/src/StrawberryShake/CodeGeneration/StrawberryShake.CodeGeneration.sln +++ b/src/StrawberryShake/CodeGeneration/StrawberryShake.CodeGeneration.sln @@ -25,12 +25,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.Transport.I EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.Resources", "..\Client\src\Resources\StrawberryShake.Resources.csproj", "{1ED745A9-4E9E-48C0-BEF3-FC0A586C797A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.CodeGeneration.CSharp.Client", "src\CodeGeneration.CSharp.Client\StrawberryShake.CodeGeneration.CSharp.Client.csproj", "{BF8AA812-4BA2-447C-BD67-C8F36C204F28}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.CodeGeneration.CSharp.Server", "src\CodeGeneration.CSharp.Server\StrawberryShake.CodeGeneration.CSharp.Server.csproj", "{3997A75C-F761-4C8C-AF51-60E55D71F0CC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrawberryShake.CodeGeneration.CSharp.Server.Tests", "test\CodeGeneration.CSharp.Server.Tests\StrawberryShake.CodeGeneration.CSharp.Server.Tests.csproj", "{450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -140,42 +134,6 @@ Global {1ED745A9-4E9E-48C0-BEF3-FC0A586C797A}.Release|x64.Build.0 = Release|Any CPU {1ED745A9-4E9E-48C0-BEF3-FC0A586C797A}.Release|x86.ActiveCfg = Release|Any CPU {1ED745A9-4E9E-48C0-BEF3-FC0A586C797A}.Release|x86.Build.0 = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|x64.ActiveCfg = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|x64.Build.0 = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|x86.ActiveCfg = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Debug|x86.Build.0 = Debug|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|Any CPU.Build.0 = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|x64.ActiveCfg = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|x64.Build.0 = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|x86.ActiveCfg = Release|Any CPU - {BF8AA812-4BA2-447C-BD67-C8F36C204F28}.Release|x86.Build.0 = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|x64.ActiveCfg = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|x64.Build.0 = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|x86.ActiveCfg = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Debug|x86.Build.0 = Debug|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|Any CPU.Build.0 = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|x64.ActiveCfg = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|x64.Build.0 = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|x86.ActiveCfg = Release|Any CPU - {3997A75C-F761-4C8C-AF51-60E55D71F0CC}.Release|x86.Build.0 = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|Any CPU.Build.0 = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|x64.ActiveCfg = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|x64.Build.0 = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|x86.ActiveCfg = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Debug|x86.Build.0 = Debug|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|Any CPU.ActiveCfg = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|Any CPU.Build.0 = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|x64.ActiveCfg = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|x64.Build.0 = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|x86.ActiveCfg = Release|Any CPU - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {92C68DD3-D7B7-493F-AFC0-1DDC847E7C58} = {86B47BC2-50C6-41EE-BFCF-E3FBB4B3E8C1} @@ -186,8 +144,5 @@ Global {72D80D07-70FF-4851-B31E-C33059647F55} = {203532CA-11E1-4514-95D5-1CBA65028301} {C249754D-6B5B-4F3E-9CD7-1B67329FDD2D} = {203532CA-11E1-4514-95D5-1CBA65028301} {1ED745A9-4E9E-48C0-BEF3-FC0A586C797A} = {203532CA-11E1-4514-95D5-1CBA65028301} - {BF8AA812-4BA2-447C-BD67-C8F36C204F28} = {86B47BC2-50C6-41EE-BFCF-E3FBB4B3E8C1} - {3997A75C-F761-4C8C-AF51-60E55D71F0CC} = {86B47BC2-50C6-41EE-BFCF-E3FBB4B3E8C1} - {450EF3F5-ADD6-43BB-B4D6-7B89D56ED726} = {5C398E96-255E-4761-9416-89C28ACC468D} EndGlobalSection EndGlobal diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocument.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocument.cs deleted file mode 100644 index 0683bbcb0e9..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocument.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public sealed class GeneratorDocument -{ - public GeneratorDocument( - string name, - string sourceText, - GeneratorDocumentKind kind, - string? hash = null, - string? path = null) - { - Name = name; - SourceText = sourceText; - Kind = kind; - Hash = hash; - Path = path; - } - - public string Name { get; } - - public string SourceText { get; } - - public GeneratorDocumentKind Kind { get; } - - public string? Hash { get; } - - public string? Path { get; } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocumentKind.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocumentKind.cs deleted file mode 100644 index 75d74c9e60e..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorDocumentKind.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public enum GeneratorDocumentKind -{ - CSharp = 0, - Razor = 1, - GraphQL = 2 -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorError.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorError.cs deleted file mode 100644 index a444e1f6977..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorError.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public sealed class GeneratorError -{ - public GeneratorError( - string code, - string title, - string message, - string? filePath = null, - Location? location = null) - { - Code = code; - Title = title; - Message = message; - FilePath = filePath; - Location = location; - } - - public string Code { get; } - - public string Title { get; } - - public string Message { get; } - - public string? FilePath { get; } - - public Location? Location { get; } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorRequest.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorRequest.cs deleted file mode 100644 index f830d1c8cbe..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorRequest.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public sealed class GeneratorRequest -{ - public GeneratorRequest( - string configFileName, - IReadOnlyList documentFileNames, - string? rootDirectory = null, - string? defaultNamespace = null, - string? persistedQueryDirectory = null, - RequestOptions option = RequestOptions.Default) - { - ConfigFileName = configFileName ?? - throw new ArgumentNullException(nameof(configFileName)); - DocumentFileNames = documentFileNames ?? - throw new ArgumentNullException(nameof(documentFileNames)); - RootDirectory = rootDirectory ?? Path.GetDirectoryName(configFileName)!; - DefaultNamespace = defaultNamespace; - PersistedQueryDirectory = persistedQueryDirectory; - Option = option; - } - - public string ConfigFileName { get; } - - public string RootDirectory { get; } - - public IReadOnlyList DocumentFileNames { get; } - - public string? DefaultNamespace { get; } - - public string? PersistedQueryDirectory { get; } - - public RequestOptions Option { get; } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorResponse.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorResponse.cs deleted file mode 100644 index d94f8a928cc..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorResponse.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public sealed class GeneratorResponse -{ - public GeneratorResponse( - IReadOnlyList? documents = null, - IReadOnlyList? errors = null) - { - if (documents is null && errors is null) - { - throw new ArgumentNullException(nameof(documents)); - } - - Documents = documents ?? Array.Empty(); - Errors = errors ?? Array.Empty(); - } - - public IReadOnlyList Documents { get; } - - public IReadOnlyList Errors { get; } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorSink.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorSink.cs deleted file mode 100644 index 48a585f2552..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/GeneratorSink.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public static class GeneratorSink -{ - public static string Location => Path.Combine(Path.GetTempPath(), "__berry"); - - public static string ErrorLogFileName => Path.Combine(Location, "errors.log"); - - public static string CreateFileName() => Path.Combine(Location, Path.GetRandomFileName()); -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Location.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Location.cs deleted file mode 100644 index 48867399930..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Location.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public sealed class Location -{ - public Location(int line, int column) - { - Line = line; - Column = column; - } - - public int Line { get; } - - public int Column { get; } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Names.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Names.cs deleted file mode 100644 index c6a308e7a18..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/Names.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -internal static class Names -{ - public const string GeneratorRequest = nameof(GeneratorRequest); - public const string DocumentFileName = nameof(DocumentFileName); - public const string ConfigFileName = "configFileName"; - public const string RootDirectory = "rootDirectory"; - public const string DefaultNamespace = "defaultNamespace"; - public const string PersistedQueryDirectory = "persistedQueryDirectory"; - public const string Option = "option"; - public const string ErrorLocation = "Location"; - public const string Line = "line"; - public const string Column = "column"; - public const string Error = nameof(Error); - public const string Code = "code"; - public const string FilePath = "filePath"; - public const string Title = "title"; - public const string Message = nameof(Message); - public const string Document = nameof(Document); - public const string Hash = "hash"; - public const string Path = "path"; - public const string Name = "name"; - public const string SourceText = nameof(SourceText); - public const string Kind = "kind"; - public const string GeneratorResponse = nameof(GeneratorResponse); -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFlags.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFlags.cs deleted file mode 100644 index 977472aeeff..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFlags.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -public enum RequestOptions -{ - Default = 0, - ExportPersistedQueries = 1, - ExportPersistedQueriesJson = 2, - GenerateRazorComponent = 4, - GenerateCSharpClient = 8, -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFormatter.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFormatter.cs deleted file mode 100644 index e668f89ba36..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/RequestFormatter.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Runtime.Serialization; -using System.Xml.Linq; -using static StrawberryShake.CodeGeneration.CSharp.Names; -using static StrawberryShake.CodeGeneration.CSharp.RequestOptions; - -namespace StrawberryShake.CodeGeneration.CSharp; - -public static class RequestFormatter -{ - public static string Format(GeneratorRequest request) - { - var temp = GeneratorSink.Location; - - if (!Directory.Exists(temp)) - { - Directory.CreateDirectory(temp); - } - - var fileName = GeneratorSink.CreateFileName(); - - var root = new XElement(Names.GeneratorRequest); - root.Add(new XAttribute(ConfigFileName, request.ConfigFileName)); - root.Add(new XAttribute(RootDirectory, request.RootDirectory)); - root.Add(new XAttribute(DefaultNamespace, request.DefaultNamespace ?? string.Empty)); - root.Add(new XAttribute(PersistedQueryDirectory, request.PersistedQueryDirectory ?? string.Empty)); - root.Add(new XAttribute(Option, request.Option.ToString())); - - foreach (var file in request.DocumentFileNames) - { - root.Add(new XElement(DocumentFileName, file)); - } - - using FileStream fileStream = File.Create(fileName); - var document = new XDocument(); - document.Add(root); - document.Save(fileStream, SaveOptions.None); - - return fileName; - } - - public static GeneratorRequest Take(string fileName) - { - GeneratorRequest request = Parse(fileName); - File.Delete(fileName); - return request; - } - - public static GeneratorRequest Parse(string fileName) - { - using FileStream fileStream = File.OpenRead(fileName); - var document = XDocument.Load(fileStream); - - if (document.Root is null || !document.Root.Name.LocalName.Equals(Names.GeneratorRequest)) - { - throw new InvalidDataContractException("Missing the request root element."); - } - - var configFileName = document.Root.Attribute(ConfigFileName)?.Value ?? - throw new InvalidDataContractException("Missing the configFileName attribute."); - var rootDirectory = document.Root.Attribute(RootDirectory)?.Value; - var defaultNamespace = document.Root.Attribute(DefaultNamespace)?.Value; - var persistedQueryDirectory = document.Root.Attribute(PersistedQueryDirectory)?.Value; - var optionString = document.Root.Attribute(Option)?.Value; - - var documentFileNames = new List(); - - foreach (XElement documentFileName in document.Root.Elements(DocumentFileName)) - { - if (!string.IsNullOrEmpty(documentFileName.Value)) - { - documentFileNames.Add(documentFileName.Value); - } - } - - return new GeneratorRequest( - configFileName, - documentFileNames, - string.IsNullOrEmpty(rootDirectory) ? null : rootDirectory, - string.IsNullOrEmpty(defaultNamespace) ? null : defaultNamespace, - string.IsNullOrEmpty(persistedQueryDirectory) ? null : persistedQueryDirectory, - string.IsNullOrEmpty(optionString) - ? Default - : (RequestOptions)Enum.Parse(typeof(RequestOptions), optionString)); - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/ResponseFormatter.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/ResponseFormatter.cs deleted file mode 100644 index 358cd54340a..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/ResponseFormatter.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Runtime.Serialization; -using System.Xml.Linq; -using static StrawberryShake.CodeGeneration.CSharp.Names; - -namespace StrawberryShake.CodeGeneration.CSharp; - -public static class ResponseFormatter -{ - public static void Format(GeneratorResponse response, string fileName) - { - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - using FileStream fileStream = File.Create(fileName); - var document = new XDocument(); - SerializeGeneratorResponse(document, response); - document.Save(fileStream, SaveOptions.None); - } - - public static GeneratorResponse Take(string fileName) - { - GeneratorResponse response = Parse(fileName); - File.Delete(fileName); - return response; - } - - public static GeneratorResponse Parse(string fileName) - { - using FileStream fileStream = File.OpenRead(fileName); - var document = XDocument.Load(fileStream); - return DeserializeGeneratorResponse(document); - } - - private static GeneratorResponse DeserializeGeneratorResponse(XDocument document) - { - if (document.Root is null || !document.Root.Name.LocalName.Equals(Names.GeneratorResponse)) - { - throw new InvalidDataContractException("The generator response has an invalid format."); - } - - var documents = new List(); - var errors = new List(); - - foreach (XElement documentElement in document.Root.Elements(Document)) - { - documents.Add(DeserializeGeneratorDocument(documentElement)); - } - - foreach (XElement errorElement in document.Root.Elements(Error)) - { - errors.Add(DeserializeGeneratorError(errorElement)); - } - - return new GeneratorResponse(documents, errors); - } - - private static void SerializeGeneratorResponse(XDocument parent, GeneratorResponse response) - { - var responseElement = new XElement(Names.GeneratorResponse); - - foreach (GeneratorDocument document in response.Documents) - { - SerializeGeneratorDocument(responseElement, document); - } - - foreach (GeneratorError error in response.Errors) - { - SerializeGeneratorError(responseElement, error); - } - - parent.Add(responseElement); - } - - private static GeneratorDocument DeserializeGeneratorDocument(XElement documentElement) - { - XAttribute? nameAttribute = documentElement.Attribute(Name); - XAttribute? kindAttribute = documentElement.Attribute(Kind); - XElement? sourceTextElement = documentElement.Element(SourceText); - XAttribute? hashAttribute = documentElement.Attribute(Hash); - XAttribute? pathAttribute = documentElement.Attribute(Names.Path); - - if (nameAttribute is null || kindAttribute is null || sourceTextElement is null) - { - throw new InvalidDataContractException("The document has an invalid format."); - } - - return new GeneratorDocument( - nameAttribute.Value, - sourceTextElement.Value, - (GeneratorDocumentKind)Enum.Parse(typeof(GeneratorDocumentKind), kindAttribute.Value), - hashAttribute?.Value, - pathAttribute?.Value); - } - - private static void SerializeGeneratorDocument(XElement parent, GeneratorDocument document) - { - var documentElement = new XElement(Document); - documentElement.Add(new XAttribute(Name, document.Name)); - documentElement.Add(new XAttribute(Kind, document.Kind.ToString())); - documentElement.Add(new XElement(SourceText, document.SourceText)); - - if (document.Hash is not null) - { - documentElement.Add(new XAttribute(Hash, document.Hash)); - } - - if (document.Path is not null) - { - documentElement.Add(new XAttribute(Names.Path, document.Path)); - } - - parent.Add(documentElement); - } - - private static GeneratorError DeserializeGeneratorError(XElement errorElement) - { - XAttribute? codeAttribute = errorElement.Attribute(Code); - XAttribute? titleAttribute = errorElement.Attribute(Title); - XAttribute? filePathAttribute = errorElement.Attribute(FilePath); - XElement? messageElement = errorElement.Element(Message); - XElement? locationElement = errorElement.Element(ErrorLocation); - - if (messageElement is null || codeAttribute is null || titleAttribute is null) - { - throw new InvalidDataContractException("The error has an invalid format."); - } - - Location? location = null; - if (locationElement is not null) - { - location = DeserializeLocation(locationElement); - } - - return new GeneratorError( - codeAttribute.Value, - titleAttribute.Value, - messageElement.Value, - filePathAttribute?.Value, - location); - } - - private static void SerializeGeneratorError(XElement parent, GeneratorError error) - { - var errorElement = new XElement(Error); - errorElement.Add(new XAttribute(Code, error.Code)); - errorElement.Add(new XAttribute(Title, error.Title)); - - if (!string.IsNullOrEmpty(error.FilePath)) - { - errorElement.Add(new XAttribute(FilePath, error.FilePath)); - } - - errorElement.Add(new XElement(Message, error.Message)); - - if (error.Location is not null) - { - SerializeLocation(errorElement, error.Location); - } - - parent.Add(errorElement); - } - - private static Location DeserializeLocation(XElement location) - { - XAttribute? line = location.Attribute(Line); - XAttribute? column = location.Attribute(Column); - - return new Location( - line is null ? 0 : int.Parse(line.Value), - column is null ? 0 : int.Parse(column.Value)); - } - - private static void SerializeLocation(XElement parent, Location location) - { - var locationElement = new XElement(ErrorLocation); - locationElement.Add(new XAttribute(Line, location.Line)); - locationElement.Add(new XAttribute(Column, location.Column)); - parent.Add(locationElement); - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/StrawberryShake.CodeGeneration.CSharp.Client.csproj b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/StrawberryShake.CodeGeneration.CSharp.Client.csproj deleted file mode 100644 index ecdf3c707ed..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Client/StrawberryShake.CodeGeneration.CSharp.Client.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - enable - enable - true - false - - StrawberryShake.CodeGeneration.CSharp.Client - StrawberryShake.CodeGeneration.CSharp - - - diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.Generate.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.Generate.cs deleted file mode 100644 index 9924d6b7c33..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.Generate.cs +++ /dev/null @@ -1,383 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -using GlobExpressions; -using HotChocolate; -using HotChocolate.Language; -using HotChocolate.Utilities; -using StrawberryShake.Tools.Configuration; -using static System.IO.Path; -using static StrawberryShake.CodeGeneration.CSharp.ErrorHelper; -using static StrawberryShake.CodeGeneration.CSharp.ServerResources; -using Path = System.IO.Path; - -namespace StrawberryShake.CodeGeneration.CSharp; - -public static partial class CSharpGeneratorServer -{ - private static readonly SHA256 _sha256 = SHA256.Create(); - - private static async Task GenerateAsync(GeneratorRequest request) - { - try - { - var settings = await LoadSettingsAsync(request); - var documents = GetMatchingDocuments(request, settings); - - if (settings.RequestStrategy == RequestStrategy.PersistedQuery) - { - if (settings.PersistedQueryDirectory is null) - { - settings.RequestStrategy = RequestStrategy.Default; - } - } - - var result = CSharpGenerator.Generate(documents, settings); - - await TryWriteCSharpFilesAsync(result.Documents, settings); - await TryWriteRazorFilesAsync(result.Documents, settings); - await TryWritePersistedQueriesAsync(result.Documents, settings); - await TryWritePersistedQueriesJsonAsync(result.Documents, settings); - - return CreateResponse( - request.Option is RequestOptions.GenerateCSharpClient - ? Array.Empty() - : result.Documents.Where(t => t.Kind is SourceDocumentKind.CSharp).ToList(), - ConvertErrors(result.Errors)); - } - catch (GraphQLException ex) - { - return ExceptionToError(ex); - } - catch (Exception ex) - { - return ExceptionToError(ex); - } - } - - private static async Task TryWriteCSharpFilesAsync( - IReadOnlyList documents, - CSharpGeneratorServerSettings settings) - { - if (settings.Option is not RequestOptions.GenerateCSharpClient) - { - return; - } - - var generatedDirectory = IsPathRooted(settings.OutputDirectoryName) - ? settings.OutputDirectoryName - : Combine(settings.RootDirectoryName, settings.OutputDirectoryName); - - if (!Directory.Exists(generatedDirectory)) - { - Directory.CreateDirectory(generatedDirectory); - } - - var generatedFiles = new HashSet(); - - foreach (var document in - documents.Where(t => t.Kind is SourceDocumentKind.CSharp)) - { - var fileName = Combine(generatedDirectory, $"{document.Name}.g.cs"); - var exists = File.Exists(fileName); - - generatedFiles.Add(fileName); - - if (!exists || !Compare(fileName, document)) - { - if (exists) - { - File.Delete(fileName); - } - - await File.WriteAllTextAsync(fileName, document.SourceText); - } - } - - foreach (var file in Directory.GetFiles(generatedDirectory, "*.components.g.cs")) - { - generatedFiles.Add(file); - } - - foreach (var file in Directory.GetFiles(generatedDirectory, "*.g.cs")) - { - if (!generatedFiles.Contains(file)) - { - File.Delete(file); - } - } - } - - private static async Task TryWriteRazorFilesAsync( - IReadOnlyList documents, - CSharpGeneratorServerSettings settings) - { - if (!settings.RazorComponents) - { - return; - } - - var generatedDirectory = Combine(settings.RootDirectoryName, settings.OutputDirectoryName); - - if (!Directory.Exists(generatedDirectory)) - { - Directory.CreateDirectory(generatedDirectory); - } - - var generatedFiles = new HashSet(); - - foreach (var document in - documents.Where(t => t.Kind is SourceDocumentKind.Razor)) - { - var fileName = Combine(generatedDirectory, $"{document.Name}.components.g.cs"); - var exists = File.Exists(fileName); - - generatedFiles.Add(fileName); - - if (!exists || !Compare(fileName, document)) - { - if (exists) - { - File.Delete(fileName); - } - - await File.WriteAllTextAsync(fileName, document.SourceText); - } - } - - foreach (var file in Directory.GetFiles(generatedDirectory, "*.components.g.cs")) - { - if (!generatedFiles.Contains(file)) - { - File.Delete(file); - } - } - } - - private static async Task TryWritePersistedQueriesAsync( - IReadOnlyList documents, - CSharpGeneratorServerSettings settings) - { - if (settings.RequestStrategy is not RequestStrategy.PersistedQuery || - settings.Option is not RequestOptions.Default and - not RequestOptions.ExportPersistedQueries) - { - return; - } - - var persistedQueryDirectory = settings.PersistedQueryDirectory!; - - if (!Directory.Exists(persistedQueryDirectory)) - { - Directory.CreateDirectory(persistedQueryDirectory); - } - - ClearPersistedQueryDirectory(persistedQueryDirectory); - - foreach (var document in - documents.Where(t => t.Kind is SourceDocumentKind.GraphQL)) - { - var fileName = Combine(persistedQueryDirectory, $"{document.Name}.graphql"); - await File.WriteAllTextAsync(fileName, document.SourceText); - } - } - - private static async Task TryWritePersistedQueriesJsonAsync( - IReadOnlyList documents, - CSharpGeneratorServerSettings settings) - { - if (settings.RequestStrategy is not RequestStrategy.PersistedQuery || - settings.Option is not RequestOptions.ExportPersistedQueriesJson) - { - return; - } - - var persistedQueryDir = settings.PersistedQueryDirectory!; - var persistedQueryFile = Combine(persistedQueryDir, "persisted-queries.json"); - - if (!Directory.Exists(persistedQueryDir)) - { - Directory.CreateDirectory(persistedQueryDir); - } - - if (File.Exists(persistedQueryFile)) - { - File.Delete(persistedQueryFile); - } - - var files = new Dictionary(); - - foreach (var document in - documents.Where(t => t.Kind is SourceDocumentKind.GraphQL)) - { - var hash = BitConverter.ToString(ComputeHash(document)).Replace("-", ""); - files[hash] = document.SourceText; - } - - await File.WriteAllBytesAsync( - persistedQueryFile, - JsonSerializer.SerializeToUtf8Bytes(files)); - } - - private static async Task LoadSettingsAsync( - GeneratorRequest request) - { - try - { - var json = await File.ReadAllTextAsync(request.ConfigFileName); - var config = GraphQLConfig.FromJson(json); - - if (!config.Extensions.StrawberryShake.Name.IsValidGraphQLName()) - { - throw new GraphQLException(CSharpGeneratorServer_ClientName_Invalid); - } - - var generatorSettings = new CSharpGeneratorServerSettings - { - RootDirectoryName = request.RootDirectory, - OutputDirectoryName = config.Extensions.StrawberryShake.OutputDirectoryName, - ClientName = config.Extensions.StrawberryShake.Name, - Namespace = config.Extensions.StrawberryShake.Namespace ?? - request.DefaultNamespace ?? - "StrawberryShake.Generated", - RequestStrategy = config.Extensions.StrawberryShake.RequestStrategy, - StrictSchemaValidation = - config.Extensions.StrawberryShake.StrictSchemaValidation - ?? true, - NoStore = config.Extensions.StrawberryShake.NoStore ?? true, - InputRecords = config.Extensions.StrawberryShake.Records.Inputs, - RazorComponents = config.Extensions.StrawberryShake.RazorComponents ?? false, - EntityRecords = config.Extensions.StrawberryShake.Records.Entities, - SingleCodeFile = config.Extensions.StrawberryShake.UseSingleFile ?? true, - Documents = config.Documents, - PersistedQueryDirectory = request.PersistedQueryDirectory, - HashProvider = - (config.Extensions.StrawberryShake.HashAlgorithm?.ToLowerInvariant() ?? "md5") - switch - { - "sha1" => new Sha1DocumentHashProvider(HashFormat.Hex), - "sha256" => new Sha256DocumentHashProvider(HashFormat.Hex), - "md5" => new MD5DocumentHashProvider(HashFormat.Hex), - _ => new Sha1DocumentHashProvider(HashFormat.Hex) - }, - Option = request.Option - }; - - if (config.Extensions.StrawberryShake.TransportProfiles - .Where(t => !string.IsNullOrEmpty(t.Name)) - .ToList() is { Count: > 0 } profiles) - { - generatorSettings.TransportProfiles.Clear(); - - foreach (var profile in profiles) - { - generatorSettings.TransportProfiles.Add( - new TransportProfile( - profile.Name, - profile.Default, - profile.Query, - profile.Mutation, - profile.Subscription)); - } - } - - switch (request.Option) - { - case RequestOptions.ExportPersistedQueries: - generatorSettings.RazorComponents = false; - generatorSettings.RequestStrategy = RequestStrategy.PersistedQuery; - break; - - case RequestOptions.ExportPersistedQueriesJson: - generatorSettings.RazorComponents = false; - generatorSettings.RequestStrategy = RequestStrategy.PersistedQuery; - break; - - case RequestOptions.GenerateRazorComponent: - generatorSettings.RazorComponents = true; - generatorSettings.RequestStrategy = RequestStrategy.Default; - break; - - case RequestOptions.GenerateCSharpClient: - generatorSettings.RazorComponents = false; - generatorSettings.RequestStrategy = RequestStrategy.Default; - break; - } - - return generatorSettings; - } - catch (Exception ex) - { - throw new GraphQLException(ex.Message); - } - } - - private static IReadOnlyList GetMatchingDocuments( - GeneratorRequest request, - CSharpGeneratorServerSettings settings) - { - var rootDirectory = request.RootDirectory; - - var files = Glob.Files(rootDirectory, settings.Documents) - .Select(t => Combine(rootDirectory, t)) - .ToArray(); - - return files; - } - - private static GeneratorResponse CreateResponse( - IReadOnlyList sourceDocuments, - IReadOnlyList errors) - { - var generatorDocuments = new List(); - - foreach (var sourceDocument in sourceDocuments) - { - generatorDocuments.Add( - new GeneratorDocument( - sourceDocument.Name, - sourceDocument.SourceText, - (GeneratorDocumentKind)(int)sourceDocument.Kind, - sourceDocument.Hash, - sourceDocument.Path)); - } - - return new GeneratorResponse(generatorDocuments, errors); - } - - private static void ClearPersistedQueryDirectory(string persistedQueryDirectory) - { - foreach (var fileName in Directory.GetFiles(persistedQueryDirectory, "*.graphql")) - { - try - { - File.Delete(fileName); - } - catch - { - // We ignore if we cannot delete a file. - // We will report on write that there is and issue. - } - } - } - - private static bool Compare(string fileName, SourceDocument document) - => ComputeHash(fileName).SequenceEqual(ComputeHash(document)); - - private static byte[] ComputeHash(string fileName) - { - using var stream = File.OpenRead(fileName); - return _sha256.ComputeHash(stream); - } - - private static byte[] ComputeHash(SourceDocument document) - { - var buffer = Encoding.UTF8.GetBytes(document.SourceText); - return _sha256.ComputeHash(buffer); - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.cs deleted file mode 100644 index 081b801fadc..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServer.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; - -namespace StrawberryShake.CodeGeneration.CSharp; - -public static partial class CSharpGeneratorServer -{ - public static async Task RunAsync(string fileSink) - { - try - { - return await ProcessAsync(fileSink); - } - catch(Exception ex) - { - await File.WriteAllTextAsync( - GeneratorSink.ErrorLogFileName, - ex.Message + Environment.NewLine + ex.StackTrace); - return 1; - } - } - - private static async Task ProcessAsync(string fileSink) - { - try - { - var request = RequestFormatter.Take(fileSink); - var response = await GenerateAsync(request); - ResponseFormatter.Format(response, fileSink); - return 0; - } - catch (Exception ex) - { - ResponseFormatter.Format( - new GeneratorResponse( - Array.Empty(), - new[] - { - new GeneratorError( - "SSG0004", - "Generator Error", - ex.Message + Environment.NewLine + ex.StackTrace) - }), - fileSink); - return 1; - } - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServerSettings.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServerSettings.cs deleted file mode 100644 index 1da7f391ba8..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/CSharpGeneratorServerSettings.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -/// -/// The csharp generator server settings. -/// -public class CSharpGeneratorServerSettings : CSharpGeneratorSettings -{ - /// - /// The GraphQL File Glob Filter. - /// - public string Documents { get; set; } = "**/*.graphql"; - - /// - /// The directory where the code generation shall copy the files to. - /// - public string? PersistedQueryDirectory { get; set; } - - /// - /// The root directory where the GraphQL client is located. - /// - public string RootDirectoryName { get; set; } = "./"; - - /// - /// The relative output directory for generated code. - /// - public string OutputDirectoryName { get; set; } = "Generated"; - - /// - /// Additional request options. - /// - public RequestOptions Option { get; set; } = RequestOptions.Default; -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorCodes.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorCodes.cs deleted file mode 100644 index b20ba8695ef..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorCodes.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -internal static class ErrorCodes -{ - public const string ParameterValidation = "SSG0001"; - - /// - /// Unexpected generator error. - /// - public const string Unexpected = "SSG0002"; -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorHelper.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorHelper.cs deleted file mode 100644 index 3b2c3d7328f..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorHelper.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using HotChocolate; -using static StrawberryShake.CodeGeneration.ErrorHelper; -using static StrawberryShake.CodeGeneration.CSharp.ErrorCodes; - -namespace StrawberryShake.CodeGeneration.CSharp; - -internal static class ErrorHelper -{ - public static IReadOnlyList ConvertErrors(IReadOnlyList errors) - { - var generatorErrors = new GeneratorError[errors.Count]; - - for (var i = 0; i < errors.Count; i++) - { - generatorErrors[i] = ConvertError(errors[i]); - } - - return generatorErrors; - } - - private static GeneratorError ConvertError(IError error) - { - var title = - error.Extensions is not null && - error.Extensions.TryGetValue(TitleExtensionKey, out var value) && - value is string s ? s : nameof(Unexpected); - - var code = error.Code ?? Unexpected; - - if (error is { Locations: { Count: > 0 } locations, Extensions: { } } && - error.Extensions.TryGetValue(FileExtensionKey, out value) && - value is string filePath) - { - return new GeneratorError( - code, - title, - error.Message, - filePath, - ConvertLocation(locations)); - } - - return new GeneratorError( - code, - title, - error.Message); - } - - private static Location ConvertLocation(IEnumerable locations) - { - var loc = locations.First(); - return new Location(loc.Line, loc.Column); - } - - public static GeneratorResponse ExceptionToError(GraphQLException exception) - => new(errors: ConvertErrors(exception.Errors)); - - public static GeneratorResponse ExceptionToError(Exception exception) - => new(errors: new[] - { - new GeneratorError( - ParameterValidation, - ErrorTitles.Generator, - exception.Message) - }); -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorTitles.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorTitles.cs deleted file mode 100644 index 930a4295078..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ErrorTitles.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace StrawberryShake.CodeGeneration.CSharp; - -internal static class ErrorTitles -{ - public const string Generator = nameof(Generator); -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/Program.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/Program.cs deleted file mode 100644 index 06401cfa7d9..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/Program.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; - -namespace StrawberryShake.CodeGeneration.CSharp; - -static class Program -{ - static async Task Main(string[] args) - { - if (args.Length != 1) - { - Console.WriteLine(ServerResources.Main_No_Arguments); - return 1; - } - - if (!File.Exists(args[0])) - { - Console.WriteLine(ServerResources.Main_Request_File_Does_Not_Exist); - return 1; - } - - return await CSharpGeneratorServer.RunAsync(args[0]); - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.Designer.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.Designer.cs deleted file mode 100644 index 49d31ce5fde..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.Designer.cs +++ /dev/null @@ -1,66 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace StrawberryShake.CodeGeneration.CSharp { - using System; - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ServerResources { - - private static System.Resources.ResourceManager resourceMan; - - private static System.Globalization.CultureInfo resourceCulture; - - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ServerResources() { - } - - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - internal static System.Resources.ResourceManager ResourceManager { - get { - if (object.Equals(null, resourceMan)) { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("StrawberryShake.CodeGeneration.CSharp.ServerResources", typeof(ServerResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - internal static System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - internal static string Main_No_Arguments { - get { - return ResourceManager.GetString("Main_No_Arguments", resourceCulture); - } - } - - internal static string Main_Request_File_Does_Not_Exist { - get { - return ResourceManager.GetString("Main_Request_File_Does_Not_Exist", resourceCulture); - } - } - - internal static string CSharpGeneratorServer_ClientName_Invalid { - get { - return ResourceManager.GetString("CSharpGeneratorServer_ClientName_Invalid", resourceCulture); - } - } - } -} diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.resx b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.resx deleted file mode 100644 index f08912bf6a5..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.resx +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - text/microsoft-resx - - - 1.3 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - You must pass in the request file name. - - - The specified request file name is invalid. - - - The client name is invalid. - - diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/StrawberryShake.CodeGeneration.CSharp.Server.csproj b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/StrawberryShake.CodeGeneration.CSharp.Server.csproj deleted file mode 100644 index 35920859972..00000000000 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/StrawberryShake.CodeGeneration.CSharp.Server.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - BerryCodeGen - StrawberryShake.CodeGeneration.CSharp - false - false - false - - - - Exe - enable - - - - - - - - - - ResXFileCodeGenerator - ServerResources.Designer.cs - - - True - True - ServerResources.resx - - - - - - - - diff --git a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/CSharpGenerator.cs b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/CSharpGenerator.cs index 1f1310bdb6d..6b2ab46eacd 100644 --- a/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/CSharpGenerator.cs +++ b/src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/CSharpGenerator.cs @@ -9,9 +9,7 @@ using HotChocolate.Language; using HotChocolate.Validation; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Options; using StrawberryShake.CodeGeneration.Analyzers; using StrawberryShake.CodeGeneration.Analyzers.Models; using StrawberryShake.CodeGeneration.CSharp.Generators; diff --git a/src/StrawberryShake/Tooling/.vscode/launch.json b/src/StrawberryShake/Tooling/.vscode/launch.json index 767264f96ce..4665d27beb3 100644 --- a/src/StrawberryShake/Tooling/.vscode/launch.json +++ b/src/StrawberryShake/Tooling/.vscode/launch.json @@ -3,7 +3,8 @@ // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", - "configurations": [{ + "configurations": [ + { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", @@ -14,12 +15,9 @@ "/Users/michael/local/play/StrawberryBuildTests", "-o /Users/michael/local/play/StrawberryBuildTests/obj/Debug/net7.0/berry/", "-q /Users/michael/local/play/StrawberryBuildTests/obj/Debug/net7.0/berry/q", - "-n StrawberryBuildTests", - "-a md5", - "-s", - "-t", - "-r", - "--relayFormat" + "-n StrawberryBuildTests", + "-a md5", + "--relayFormat" ], "cwd": "${workspaceFolder}/src/dotnet-graphql", "console": "internalConsole", diff --git a/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettings.cs b/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettings.cs index 9f94d568b0a..466aa5f3069 100644 --- a/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettings.cs +++ b/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettings.cs @@ -45,13 +45,12 @@ public class StrawberryShakeSettings /// /// Defines the default request strategy. /// - public RequestStrategy RequestStrategy { get; set; } = - RequestStrategy.Default; + public RequestStrategy? RequestStrategy { get; set; } /// /// Gets or sets the name of the generated code output directory. /// - public string OutputDirectoryName { get; set; } = "Generated"; + public string? OutputDirectoryName { get; set; } /// /// Defines if a client shall be generated without a store. diff --git a/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettingsDefaults.cs b/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettingsDefaults.cs deleted file mode 100644 index c3309d0502d..00000000000 --- a/src/StrawberryShake/Tooling/src/Configuration/StrawberryShakeSettingsDefaults.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace StrawberryShake.Tools.Configuration -{ - internal static class StrawberryShakeSettingsDefaults - { - public const string Name = "Client"; - - public const bool DependencyInjection = true; - - public const bool StrictSchemaValidation = true; - - public const string HashAlgorithm = "md5"; - - public const bool UseSingleFile = true; - - public const string OutputDirectoryName = "Generated"; - - public const bool NoStore = false; - - public const bool EmitGeneratedCode = true; - } -} diff --git a/src/StrawberryShake/Tooling/src/dotnet-graphql/GenerateCommand.cs b/src/StrawberryShake/Tooling/src/dotnet-graphql/GenerateCommand.cs index 52d63dcae6a..80f01bb4b0c 100644 --- a/src/StrawberryShake/Tooling/src/dotnet-graphql/GenerateCommand.cs +++ b/src/StrawberryShake/Tooling/src/dotnet-graphql/GenerateCommand.cs @@ -62,16 +62,16 @@ public static void Build(CommandLineApplication generate) "Console output as JSON.", CommandOptionType.NoValue); - var strategy = RequestStrategy.Default; - var queryOutputDir = queryOutputDirArg.Value(); - - if (!string.IsNullOrEmpty(queryOutputDir) || relayFormatArg.HasValue()) - { - strategy = RequestStrategy.PersistedQuery; - } - generate.OnExecuteAsync(ct => { + var strategy = RequestStrategy.Default; + var queryOutputDir = queryOutputDirArg.Value(); + + if (!string.IsNullOrEmpty(queryOutputDir) || relayFormatArg.HasValue()) + { + strategy = RequestStrategy.PersistedQuery; + } + var arguments = new GenerateCommandArguments( pathArg.Value ?? CurrentDirectory, rootNamespaceArg.Value(), @@ -116,10 +116,10 @@ public GenerateCommandHandler(IConsoleOutput output) var result = GenerateClient(settings.ClientName, documents, settings); var outputDir = args.OutputDir ?? Path.Combine( Path.GetDirectoryName(configFileName)!, - config.Extensions.StrawberryShake.OutputDirectoryName); + config.Extensions.StrawberryShake.OutputDirectoryName ?? "Generated"); var queryOutputDir = args.QueryOutputDir ?? Path.Combine( Path.GetDirectoryName(configFileName)!, - config.Extensions.StrawberryShake.OutputDirectoryName, + config.Extensions.StrawberryShake.OutputDirectoryName ?? "Generated", "Queries"); if (result.HasErrors()) @@ -129,7 +129,7 @@ public GenerateCommandHandler(IConsoleOutput output) } else { - await WriteCodeFilesAsync(result, outputDir, cancellationToken); + await WriteCodeFilesAsync(clientName, result, outputDir, cancellationToken); if (args.Strategy is RequestStrategy.PersistedQuery) { @@ -146,8 +146,8 @@ public GenerateCommandHandler(IConsoleOutput output) } private CSharpGeneratorResult GenerateClient( - string clientName, - string[] documents, + string clientName, + string[] documents, CSharpGeneratorSettings settings) { using var activity = Output.WriteActivity($"Generate {clientName}"); @@ -155,10 +155,19 @@ public GenerateCommandHandler(IConsoleOutput output) } private async Task WriteCodeFilesAsync( + string clientName, CSharpGeneratorResult result, string outputDir, CancellationToken cancellationToken) { + if (Directory.Exists(outputDir)) + { + foreach (var oldFile in Directory.GetFiles(outputDir, $"{clientName}.*.cs")) + { + File.Delete(oldFile); + } + } + foreach (var doc in result.Documents) { if (doc.Kind is SourceDocumentKind.CSharp or SourceDocumentKind.Razor) @@ -189,7 +198,10 @@ public GenerateCommandHandler(IConsoleOutput output) foreach (var doc in result.Documents) { - map[doc.Hash!] = doc.SourceText; + if (doc.Kind is SourceDocumentKind.GraphQL) + { + map[doc.Hash!] = doc.SourceText; + } } var fileName = Path.Combine(outputDir, "queries.json"); @@ -203,6 +215,14 @@ public GenerateCommandHandler(IConsoleOutput output) } else { + if (Directory.Exists(outputDir)) + { + foreach (var oldFile in Directory.GetFiles(outputDir, "*.graphql")) + { + File.Delete(oldFile); + } + } + foreach (var doc in result.Documents) { var fileName = Path.Combine(outputDir, $"{doc.Hash}.graphql"); @@ -273,8 +293,13 @@ internal sealed class GenerateCommandArguments RazorComponents = razorComponents; OutputDir = outputDir; Strategy = strategy; - QueryOutputDir = queryOutputDir ?? outputDir; RelayFormat = relayFormat; + QueryOutputDir = queryOutputDir; + + if (queryOutputDir is null && outputDir is not null) + { + QueryOutputDir = System.IO.Path.Combine(outputDir, "Queries"); + } } public string Path { get; } diff --git a/src/StrawberryShake/Tooling/src/dotnet-graphql/GeneratorHelpers.cs b/src/StrawberryShake/Tooling/src/dotnet-graphql/GeneratorHelpers.cs index fe4ef5dc858..3fae1179438 100644 --- a/src/StrawberryShake/Tooling/src/dotnet-graphql/GeneratorHelpers.cs +++ b/src/StrawberryShake/Tooling/src/dotnet-graphql/GeneratorHelpers.cs @@ -55,9 +55,9 @@ public static string[] GetGraphQLDocuments(string path, string pattern) EntityRecords = configSettings.Records.Entities, RazorComponents = configSettings.RazorComponents ?? args.RazorComponents, SingleCodeFile = configSettings.UseSingleFile ?? args.UseSingleFile, - RequestStrategy = configSettings.RequestStrategy, + RequestStrategy = configSettings.RequestStrategy ?? args.Strategy, HashProvider = GetHashProvider(configSettings.HashAlgorithm ?? args.HashAlgorithm), - TransportProfiles = MapTransportProfiles(configSettings.TransportProfiles) + TransportProfiles = MapTransportProfiles(configSettings.TransportProfiles), }; } diff --git a/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandContext.cs b/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandContext.cs index 8430944d344..0935202f532 100644 --- a/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandContext.cs +++ b/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandContext.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using StrawberryShake.Tools.Configuration; namespace StrawberryShake.Tools @@ -36,6 +34,5 @@ public class InitCommandContext public string? Scheme { get; } public Dictionary> CustomHeaders { get; } public string? CustomNamespace { get; set; } - public bool UseDependencyInjection { get; set; } = true; } } diff --git a/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandHandler.cs b/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandHandler.cs index d0e29b36657..59049e4c1b2 100644 --- a/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandHandler.cs +++ b/src/StrawberryShake/Tooling/src/dotnet-graphql/InitCommandHandler.cs @@ -122,8 +122,7 @@ await arguments.AuthArguments { Name = context.ClientName, Namespace = context.CustomNamespace, - Url = context.Uri!.ToString(), - DependencyInjection = context.UseDependencyInjection + Url = context.Uri!.ToString() } } };