Skip to content

A Swiss Army knife for developers.

refactoring JSON format to externalize to the JSON helper the formatting (#31)

BenjaminT86ad20fb7a70
diff --git a/src/dev/impl/DevToys/DevToys.csproj b/src/dev/impl/DevToys/DevToys.csproj
index d9479481b..f49f90b9b 100644
--- a/src/dev/impl/DevToys/DevToys.csproj
+++ b/src/dev/impl/DevToys/DevToys.csproj
@@ -193,6 +193,8 @@
<Compile Include="Core\Threading\ThreadPriority.cs" />
<Compile Include="Core\TitleBar.cs" />
<Compile Include="Core\ToolProviderFactory.cs" />
+ <Compile Include="Models\IndentationDisplayPair.cs" />
+ <Compile Include="Models\Indentation.cs" />
<Compile Include="UI\Controls\CodeEditor.xaml.cs">
<DependentUpon>CodeEditor.xaml</DependentUpon>
</Compile>
diff --git a/src/dev/impl/DevToys/Helpers/JsonHelper.cs b/src/dev/impl/DevToys/Helpers/JsonHelper.cs
index 9d557eea1..d667aaf96 100644
--- a/src/dev/impl/DevToys/Helpers/JsonHelper.cs
+++ b/src/dev/impl/DevToys/Helpers/JsonHelper.cs
@@ -1,9 +1,12 @@
#nullable enable
using DevToys.Core;
+using DevToys.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
+using System.IO;
+using System.Text;
namespace DevToys.Helpers
{
@@ -12,7 +15,7 @@ namespace DevToys.Helpers
/// <summary>
/// Detects whether the given string is a valid JSON or not.
/// </summary>
- internal static bool IsValidJson(string? input)
+ internal static bool IsValid(string? input)
{
if (string.IsNullOrWhiteSpace(input))
{
@@ -45,5 +48,66 @@ namespace DevToys.Helpers
return false;
}
}
+
+ /// <summary>
+ /// Format a string to the specified JSON format.
+ /// </summary>
+ internal static string Format(string? input, Indentation indentationMode)
+ {
+ if (!IsValid(input))
+ {
+ return string.Empty;
+ }
+
+ try
+ {
+ JToken? jtoken = JToken.Parse(input!);
+ if (jtoken is not null)
+ {
+ var stringBuilder = new StringBuilder();
+ using (var stringWriter = new StringWriter(stringBuilder))
+ using (var jsonTextWriter = new JsonTextWriter(stringWriter))
+ {
+ switch (indentationMode)
+ {
+ case Indentation.TwoSpaces:
+ jsonTextWriter.Formatting = Formatting.Indented;
+ jsonTextWriter.IndentChar = ' ';
+ jsonTextWriter.Indentation = 2;
+ break;
+ case Indentation.FourSpaces:
+ jsonTextWriter.Formatting = Formatting.Indented;
+ jsonTextWriter.IndentChar = ' ';
+ jsonTextWriter.Indentation = 4;
+ break;
+ case Indentation.OneTab:
+ jsonTextWriter.Formatting = Formatting.Indented;
+ jsonTextWriter.IndentChar = '\t';
+ jsonTextWriter.Indentation = 1;
+ break;
+ case Indentation.Minified:
+ jsonTextWriter.Formatting = Formatting.None;
+ break;
+ default:
+ throw new NotSupportedException();
+ }
+ jtoken.WriteTo(jsonTextWriter);
+ }
+
+ return stringBuilder.ToString();
+ }
+
+ return string.Empty;
+ }
+ catch (JsonReaderException ex)
+ {
+ return ex.Message;
+ }
+ catch (Exception ex) //some other exception
+ {
+ Logger.LogFault("Json formatter", ex, $"Indentation: {indentationMode}");
+ return ex.Message;
+ }
+ }
}
}
diff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.cs
index 4d5cfc677..31733cbf6 100644
--- a/src/dev/impl/DevToys/LanguageManager.cs
+++ b/src/dev/impl/DevToys/LanguageManager.cs
@@ -108,6 +108,12 @@ namespace DevToys
Culture = new CultureInfo("en")
},
new LanguageDefinition
+ {
+ Identifier = "russian",
+ DisplayName = "Русский",
+ Culture = new CultureInfo("ru")
+ },
+ new LanguageDefinition
{
Identifier = "french",
DisplayName = "français",
@@ -744,4 +750,4 @@ namespace DevToys
/// </summary>
public string RightText => _resources.GetString("RightText");
}
-}
\ No newline at end of file
+}
diff --git a/src/dev/impl/DevToys/Models/Indentation.cs b/src/dev/impl/DevToys/Models/Indentation.cs
new file mode 100644
index 000000000..a19e7e160
--- /dev/null
+++ b/src/dev/impl/DevToys/Models/Indentation.cs
@@ -0,0 +1,10 @@
+namespace DevToys.Models
+{
+ public enum Indentation
+ {
+ TwoSpaces,
+ FourSpaces,
+ OneTab,
+ Minified
+ }
+}
diff --git a/src/dev/impl/DevToys/Models/IndentationDisplayPair.cs b/src/dev/impl/DevToys/Models/IndentationDisplayPair.cs
new file mode 100644
index 000000000..e51da4fec
--- /dev/null
+++ b/src/dev/impl/DevToys/Models/IndentationDisplayPair.cs
@@ -0,0 +1,32 @@
+using System;
+
+namespace DevToys.Models
+{
+ public class IndentationDisplayPair : IEquatable<IndentationDisplayPair>
+ {
+ private static JsonFormatterStrings Strings => LanguageManager.Instance.JsonFormatter;
+
+ public static readonly IndentationDisplayPair TwoSpaces = new IndentationDisplayPair(Strings.TwoSpaces, Indentation.TwoSpaces);
+
+ public static readonly IndentationDisplayPair FourSpaces = new IndentationDisplayPair(Strings.FourSpaces, Indentation.FourSpaces);
+
+ public static readonly IndentationDisplayPair OneTab = new IndentationDisplayPair(Strings.OneTab, Indentation.OneTab);
+
+ public static readonly IndentationDisplayPair Minified = new IndentationDisplayPair(Strings.Minified, Indentation.Minified);
+
+ public string DisplayName { get; }
+
+ public Indentation Value { get; }
+
+ private IndentationDisplayPair(string displayName, Indentation value)
+ {
+ DisplayName = displayName;
+ Value = value;
+ }
+
+ public bool Equals(IndentationDisplayPair other)
+ {
+ return other.Value == Value;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
index c5ed4b006..f258d191b 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
@@ -28,7 +28,7 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
public bool CanBeTreatedByTool(string data)
{
- return JsonHelper.IsValidJson(data);
+ return JsonHelper.IsValid(data);
}
public IToolViewModel CreateTool()
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
index 841f8ad47..3a6f06d94 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
@@ -2,17 +2,16 @@
using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
-using DevToys.Core;
using DevToys.Core.Threading;
+using DevToys.Helpers;
+using DevToys.Models;
using DevToys.Views.Tools.JsonFormatter;
using Microsoft.Toolkit.Mvvm.ComponentModel;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Composition;
-using System.IO;
-using System.Text;
+using System.Linq;
using System.Threading.Tasks;
namespace DevToys.ViewModels.Tools.JsonFormatter
@@ -23,16 +22,11 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
/// <summary>
/// The indentation to apply while formatting.
/// </summary>
- private static readonly SettingDefinition<string> Indentation
+ private static readonly SettingDefinition<Indentation> Indentation
= new(
- name: $"{nameof(JsonFormatterToolViewModel)}.{nameof(Indentation)}",
+ name: $"{nameof(JsonFormatter.JsonFormatterToolViewModel)}.{nameof(Indentation)}",
isRoaming: true,
- defaultValue: TwoSpaceIndentation);
-
- private const string TwoSpaceIndentation = "TwoSpaces";
- private const string FourSpaceIndentation = "FourSpaces";
- private const string OneTabIndentation = "OneTab";
- private const string NoIndentation = "Minified";
+ defaultValue: Models.Indentation.TwoSpaces);
private readonly Queue<string> _formattingQueue = new();
@@ -47,20 +41,35 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
/// <summary>
/// Gets or sets the desired indentation.
/// </summary>
- internal string IndentationMode
+ internal IndentationDisplayPair IndentationMode
{
- get => SettingsProvider.GetSetting(Indentation);
+ get
+ {
+ Indentation settingsValue = SettingsProvider.GetSetting(Indentation);
+ var indentation = Indentations.FirstOrDefault(x => x.Value == settingsValue);
+ return indentation ?? Models.IndentationDisplayPair.TwoSpaces;
+ }
set
{
- if (!string.Equals(SettingsProvider.GetSetting(Indentation), value, StringComparison.Ordinal))
+ if (!IndentationMode.Equals(value))
{
- SettingsProvider.SetSetting(Indentation, value);
+ SettingsProvider.SetSetting(Indentation, value.Value);
OnPropertyChanged();
QueueFormatting();
}
}
}
+ /// <summary>
+ /// Get a list of supported Indentation
+ /// </summary>
+ internal IReadOnlyList<IndentationDisplayPair> Indentations = new ObservableCollection<IndentationDisplayPair> {
+ Models.IndentationDisplayPair.TwoSpaces,
+ Models.IndentationDisplayPair.FourSpaces,
+ Models.IndentationDisplayPair.OneTab,
+ Models.IndentationDisplayPair.Minified,
+ };
+
/// <summary>
/// Gets or sets the input text.
/// </summary>
@@ -82,7 +91,6 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
internal ISettingsProvider SettingsProvider { get; }
-
[ImportingConstructor]
public JsonFormatterToolViewModel(ISettingsProvider settingsProvider)
{
@@ -108,83 +116,17 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
while (_formattingQueue.TryDequeue(out string text))
{
- var success = FormatJson(text, out string result);
-
- ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>
- {
- OutputValue = result;
- }).ForgetSafely();
- }
-
- _formattingInProgress = false;
- }
-
- private bool FormatJson(string input, out string output)
- {
- if (string.IsNullOrWhiteSpace(input))
- {
- output = string.Empty;
- return false;
- }
-
- try
- {
- JToken? jtoken = JToken.Parse(input);
- if (jtoken is not null)
+ string? result = JsonHelper.Format(text, IndentationMode.Value);
+ if (result != null)
{
- var stringBuilder = new StringBuilder();
- using (var stringWriter = new StringWriter(stringBuilder))
- using (var jsonTextWriter = new JsonTextWriter(stringWriter))
+ ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>
{
- switch (IndentationMode)
- {
- case TwoSpaceIndentation:
- jsonTextWriter.Formatting = Formatting.Indented;
- jsonTextWriter.IndentChar = ' ';
- jsonTextWriter.Indentation = 2;
- break;
-
- case FourSpaceIndentation:
- jsonTextWriter.Formatting = Formatting.Indented;
- jsonTextWriter.IndentChar = ' ';
- jsonTextWriter.Indentation = 4;
- break;
-
- case OneTabIndentation:
- jsonTextWriter.Formatting = Formatting.Indented;
- jsonTextWriter.IndentChar = '\t';
- jsonTextWriter.Indentation = 1;
- break;
-
- case NoIndentation:
- jsonTextWriter.Formatting = Formatting.None;
- break;
-
- default:
- throw new NotSupportedException();
- }
-
- jtoken.WriteTo(jsonTextWriter);
- }
-
- output = stringBuilder.ToString();
- return true;
+ OutputValue = result;
+ }).ForgetSafely();
}
-
- output = string.Empty;
- return false;
- }
- catch (JsonReaderException ex)
- {
- output = ex.Message;
- return false;
- }
- catch (Exception ex) //some other exception
- {
- Logger.LogFault("Json formatter", ex, $"Indentation: {IndentationMode}");
- output = ex.Message;
- return false;
}
+
+ _formattingInProgress = false;
}
}
}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolProvider.cs
index 4041c6b33..f909a9d7e 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolProvider.cs
@@ -28,7 +28,7 @@ namespace DevToys.ViewModels.Tools.JsonYaml
public bool CanBeTreatedByTool(string data)
{
- return JsonHelper.IsValidJson(data) || YamlHelper.IsValidYaml(data);
+ return JsonHelper.IsValid(data) || YamlHelper.IsValidYaml(data);
}
public IToolViewModel CreateTool()
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
index ddb11e7fd..3f0fef000 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
@@ -78,7 +78,7 @@ namespace DevToys.ViewModels.Tools.JsonYaml
if (string.Equals(value, JsonToYaml))
{
- if (JsonHelper.IsValidJson(OutputValue))
+ if (JsonHelper.IsValid(OutputValue))
{
InputValue = OutputValue;
}
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
index ae0bc4a9b..33f9c98c4 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
@@ -32,12 +32,9 @@
<FontIcon Glyph="&#xF6F8;" />
</controls:ExpandableSettingControl.Icon>
<ComboBox
- SelectedValuePath="Tag"
+ ItemsSource="{x:Bind ViewModel.Indentations}"
+ DisplayMemberPath="DisplayName"
SelectedValue="{x:Bind ViewModel.IndentationMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
- <ComboBoxItem Tag="TwoSpaces" Content="{x:Bind ViewModel.Strings.TwoSpaces}"/>
- <ComboBoxItem Tag="FourSpaces" Content="{x:Bind ViewModel.Strings.FourSpaces}"/>
- <ComboBoxItem Tag="OneTab" Content="{x:Bind ViewModel.Strings.OneTab}"/>
- <ComboBoxItem Tag="Minified" Content="{x:Bind ViewModel.Strings.Minified}"/>
</ComboBox>
</controls:ExpandableSettingControl>
</StackPanel>
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
index 273a875b4..de6705093 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
+++ b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
@@ -47,7 +47,7 @@ namespace DevToys.Views.Tools.JsonYaml
if (!string.IsNullOrWhiteSpace(parameters.ClipBoardContent))
{
- if (JsonHelper.IsValidJson(parameters.ClipBoardContent!))
+ if (JsonHelper.IsValid(parameters.ClipBoardContent!))
{
ViewModel.ConversionMode = JsonYamlToolViewModel.JsonToYaml;
}
diff --git a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
index c8a4805c4..cc89a5fae 100644
--- a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
+++ b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
@@ -1,4 +1,5 @@
using DevToys.Helpers;
+using DevToys.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DevToys.Tests.Helpers
@@ -13,9 +14,64 @@ namespace DevToys.Tests.Helpers
[DataRow(" { } ", true)]
[DataRow(" { \"foo\": 123 } ", true)]
[DataRow(" bar { \"foo\": 123 } ", false)]
- public void IsValidJson(string input, bool expectedResult)
+ public void IsValid(string input, bool expectedResult)
{
- Assert.AreEqual(expectedResult, JsonHelper.IsValidJson(input));
+ Assert.AreEqual(expectedResult, JsonHelper.IsValid(input));
+ }
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ [DataRow(" { } ", "{}")]
+ [DataRow(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]
+ public void FormatTwoSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, IndentationDisplayPair.TwoSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ [DataRow(" { } ", "{}")]
+ [DataRow(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]
+ public void FormatFourSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, IndentationDisplayPair.FourSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ [DataRow(" { } ", "{}")]
+ [DataRow(" { \"foo\": 123 } ", "{\r\n\t\"foo\": 123\r\n}")]
+ public void FormatOneTab(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, IndentationDisplayPair.OneTab));
+ }
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ [DataRow(" { } ", "{}")]
+ [DataRow(" { \"foo\": 123 } ", "{\"foo\":123}")]
+ public void FormatMinified(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, IndentationDisplayPair.Minified));
+ }
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ [DataRow(" { } ", "")]
+ [DataRow(" { \"foo\": 123 } ", "")]
+ public void FormatNullIndentation(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, null));
}
}
}