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

Feature/json generator #36

Merged
merged 2 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 42 additions & 20 deletions src/WireMockInspector/CodeGenerators/MappingCodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ private static string ReadEmbeddedResource(string resourceName)
using StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
public const string DefaultTemplateName = "(default)";
public const string DefaultTemplateForCSharp = "C# (default)";
public const string DefaultTemplateForJSON = "JSON (default)";


private static JToken? TryParseJson(string? payload)
Expand All @@ -75,10 +76,21 @@ private static string ReadEmbeddedResource(string resourceName)
}
}

public static string GenerateCSharpCode(LogRequestModel logRequest, LogResponseModel logResponse, MappingCodeGeneratorConfigViewModel config)
private static string EscapeStringForJson(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}

return JsonConvert.SerializeObject(value);
}

public static MarkdownCode GenerateCode(LogRequestModel logRequest, LogResponseModel logResponse, MappingCodeGeneratorConfigViewModel config)
{
var options = new TemplateOptions();
options.ValueConverters.Add(o => o is JToken t? t.ToString(): null );
options.Filters.AddFilter("escape_json", (input, arguments, templateContext) => new StringValue(EscapeStringForJson(input.ToStringValue())));
options.Filters.AddFilter("escape_string_for_csharp", (input, arguments, templateContext) => new StringValue(EscapeStringForCSharp(input.ToStringValue()) ));
options.Filters.AddFilter("format_as_anonymous_object", (input, arguments, templateContext) =>
{
Expand All @@ -94,23 +106,9 @@ public static string GenerateCSharpCode(LogRequestModel logRequest, LogResponseM
_ => input
};
});

var parser = new FluidParser();

var templateCode ="";
if (config.SelectedTemplate == DefaultTemplateName)
{
templateCode = ReadEmbeddedResource("WireMockInspector.CodeGenerators.default_template.liquid");
}
else if(string.IsNullOrWhiteSpace(config.SelectedTemplate) == false)
{
var templatePath = Path.Combine(PathHelper.GetTemplateDir(), config.SelectedTemplate);
if (File.Exists(templatePath))
{
templateCode = File.ReadAllText(templatePath);
}
}


var (lang, templateCode) = GetTemplateCode(config);
if (parser.TryParse(templateCode, out var ftemplate, out var error))
{
var reader = new JsonDataSourceReader();
Expand Down Expand Up @@ -162,13 +160,37 @@ public static string GenerateCSharpCode(LogRequestModel logRequest, LogResponseM
{
data = data
}, options));
return result;
return new MarkdownCode(lang, result);
}

return error;
return new MarkdownCode("text", $"Error: {error}");

}

private static (string lang, string template) GetTemplateCode(MappingCodeGeneratorConfigViewModel config)
{
if (config.SelectedTemplate == DefaultTemplateForCSharp)
{
return ("cs", ReadEmbeddedResource("WireMockInspector.CodeGenerators.default_template.liquid"));
}

if (config.SelectedTemplate == DefaultTemplateForJSON)
{
return ("json", ReadEmbeddedResource("WireMockInspector.CodeGenerators.json_definition_template.liquid"));
}

if(string.IsNullOrWhiteSpace(config.SelectedTemplate) == false)
{
var templatePath = Path.Combine(PathHelper.GetTemplateDir(), config.SelectedTemplate);
if (File.Exists(templatePath))
{
return ("cs", File.ReadAllText(templatePath));
}
}

return ("cs",string.Empty);
}

private static string GetFullPath(LogRequestModel logRequest)
{
var query = HttpUtility.ParseQueryString("");
Expand Down
115 changes: 115 additions & 0 deletions src/WireMockInspector/CodeGenerators/json_definition_template.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
{%- assign request = data.request -%}
{%- assign response = data.response -%}
{%- assign config = data.config -%}
{
"Priority": 0,
"Request": {
{%- if config.IncludePath %}
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": {{ request.Path | escape_json }}
}
]
},
{%- endif %}
{%- if config.IncludeMethod %}
"Methods": [
{{ request.Method | escape_json }}
],
{%- endif %}
{%- if config.IncludeClientIP and request.ClientIP %}
"ClientIP": {{ request.ClientIP | escape_json }},
{%- endif %}
{%- if config.IncludeAbsolutePath and request.AbsolutePath %}
"AbsolutePath": {{ request.AbsolutePath | escape_json }},
{%- endif %}
{%- if config.IncludeUrl and request.Url %}
"Url": {{ request.Url | escape_json }},
{%- endif %}
{%- if config.IncludeAbsoluteUrl and request.AbsoluteUrl %}
"AbsoluteUrl": {{ request.AbsoluteUrl | escape_json }},
{%- endif %}
{%- if config.IncludeProxyUrl and request.ProxyUrl %}
"ProxyUrl": {{ request.ProxyUrl | escape_json }},
{%- endif %}
{%- if config.IncludeQuery and request.Query %}
"Params": [
{%- for item in request.Query %}
{%- assign query_key = item[0] %}
{%- assign query_values = item[1] %}
{
"Name": {{ query_key | escape_json }},
"Matchers": [
{%- for value in query_values %}
{
"Name": "ExactMatcher",
"Pattern": {{ value | escape_json }}
}{%- if forloop.last == false %},{% endif %}
{%- endfor %}
]
}{%- if forloop.last == false %},{% endif %}
{%- endfor %}
],
{%- endif %}
{%- if config.IncludeHeaders and request.Headers %}
"Headers": [
{%- for item in request.Headers %}
{%- assign header_key = item[0] %}
{%- assign header_values = item[1] | join: "\", \"" | escape_json %}
{
"Name": {{ header_key | escape_json }},
"Matchers": [
{
"Name": "ExactMatcher",
"Pattern": {{ header_values }}
}
]
}{%- if forloop.last == false %},{% endif %}
{%- endfor %}
],
{%- endif %}

{%- if config.IncludeBody %}
{%- if request.BodyAsJson %}
"Body": {
"Matcher": {
"Name": "WildcardMatcher",
"Pattern": {{ request.BodyAsJson | escape_json }}
}
},
{%- elsif request.Body %}
"Body": {
"Matcher": {
"Name": "WildcardMatcher",
"Pattern": {{ request.Body | escape_json }}
}
}
{%- endif %}
{%- endif %}
},
"Response": {
{%- if config.IncludeStatusCode and response.StatusCode %}
"StatusCode": {{ response.StatusCode }},
{%- endif %}
"BodyDestination": "SameAsSource",
{%- if config.IncludeHeadersResponse and response.Headers %}
"Headers": {
{%- for item in response.Headers %}
{%- assign header_key = item[0] %}
{%- assign header_values = item[1] | join: ", " | escape_json %}
{{ header_key | escape_json }}: {{ header_values }}{%- if forloop.last == false %},{% endif %}
{%- endfor %}
},
{%- endif %}
{%- if config.IncludeBodyResponse %}
{%- if response.BodyAsJson %}
"BodyAsJson": {{ response.BodyAsJson | escape_json }},
{%- elsif response.Body %}
{%- assign body = response.Body | escape_json %}
"Body": {{ body }}
{%- endif %}
{%- endif %}
}
}
8 changes: 3 additions & 5 deletions src/WireMockInspector/ViewModels/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ await _settingsManager.UpdateSettings(settings =>
Config =
{

SelectedTemplate = MappingCodeGenerator.DefaultTemplateName,
SelectedTemplate = MappingCodeGenerator.DefaultTemplateForCSharp,
Templates = GetAvailableTemplates().ToList(),
IncludeClientIP = false,
IncludePath = true,
Expand All @@ -476,15 +476,13 @@ await _settingsManager.UpdateSettings(settings =>
};
}).ToProperty(this, x=>x.CodeGenerator, out _codeGenerator);
}




private IEnumerable<string> GetAvailableTemplates()
{
var templateDir = PathHelper.GetTemplateDir();

yield return MappingCodeGenerator.DefaultTemplateName;
yield return MappingCodeGenerator.DefaultTemplateForCSharp;
yield return MappingCodeGenerator.DefaultTemplateForJSON;

foreach (var file in Directory.GetFiles(templateDir, "*.liquid"))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ public MappingCodeGeneratorViewModel()

Config.WhenAnyPropertyChanged()
.Where(x=> x is not null)
.Select(x =>
{
var code = MappingCodeGenerator.GenerateCSharpCode(Request, Response, x);
return new MarkdownCode("cs", code);
}).ToProperty(this, x => x.OutputCode, out _outputCode);
.Select(x => MappingCodeGenerator.GenerateCode(Request, Response, x))
.ToProperty(this, x => x.OutputCode, out _outputCode);
}
}
24 changes: 12 additions & 12 deletions src/WireMockInspector/Views/CodeBlockViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,28 +49,18 @@ private void OnCodeChanged(MarkdownCode newValue, MarkdownCode NewValue)
}


private void SetMarkdown(ViewModels.MarkdownCode md)
private void SetMarkdown(ViewModels.MarkdownCode md)
{
if (md is not null)
{
if (this.Document is not null)
{
this.Document.Text = md.rawValue;
}
else
{
this.Document = new TextDocument(md.rawValue);
}

if (_currentLang != md.lang)
{
_currentLang = md.lang;
CodeBlockViewer _textEditor = this;

if (_registryOptions.GetLanguageByExtension("." + md.lang) is { } languageByExtension)
{
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(languageByExtension.Id));


}


Expand All @@ -80,6 +70,16 @@ private void SetMarkdown(ViewModels.MarkdownCode md)
}
this.TextArea.TextView.LineTransformers.Add(new DiffLineBackgroundRenderer(md.oldTextLines));
}

if (this.Document is not null || _currentLang != md.lang)
{
this.Document.Text = md.rawValue;
}
else
{
this.Document = new TextDocument(md.rawValue);
}

}
else
{
Expand Down
1 change: 1 addition & 0 deletions src/WireMockInspector/WireMockInspector.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,6 @@

<ItemGroup>
<EmbeddedResource Include="CodeGenerators\default_template.liquid" />
<EmbeddedResource Include="CodeGenerators\json_definition_template.liquid" />
</ItemGroup>
</Project>
Loading