Skip to content

A Swiss Army knife for developers.

Add XML formatter and refactoring to DevToys 2.0 (#1007)

Laurel Baudoux857a6ff7e622
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 09cf52b9c..d947abb12 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -17,6 +17,7 @@ You can contribute to DevToys app by:
* ASP.NET and web development
* Node.js development
* .NET desktop development
+1. Install latest [Node.js](https://nodejs.org/).
### Finalize your environment
1. Clone this repository.
diff --git a/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs b/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs
index f68a4a6b4..d8c0f169b 100644
--- a/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs
+++ b/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs
@@ -1,10 +1,10 @@
using OneOf;
-namespace DevToys.Api.Core;
+namespace DevToys.Api;
public static class OneOfExtensions
{
- public static Task<Stream> GetStreamAsync(
+ public static Task<ResultInfo<Stream>> GetStreamAsync(
this OneOf<string, FileInfo> input,
IFileStorage fileStorage,
CancellationToken cancellationToken)
@@ -17,14 +17,22 @@ public static class OneOfExtensions
return GetStreamAsync(OneOf<FileInfo, string>.FromT1(input.AsT0), fileStorage, cancellationToken);
}
- public static Task<Stream> GetStreamAsync(
+ public static async Task<ResultInfo<Stream>> GetStreamAsync(
this OneOf<FileInfo, string> input,
IFileStorage fileStorage,
CancellationToken cancellationToken)
{
- return
+ return await
input.Match(
- inputFile => Task.FromResult(fileStorage.OpenReadFile(inputFile.FullName)),
+ async inputFile =>
+ {
+ if (!fileStorage.FileExists(inputFile.FullName))
+ {
+ return new ResultInfo<Stream>(Stream.Null, false);
+ }
+
+ return new ResultInfo<Stream>(fileStorage.OpenReadFile(inputFile.FullName), true);
+ },
async inputString =>
{
var stringStream = new MemoryStream();
@@ -35,37 +43,41 @@ public static class OneOfExtensions
}
writer.Flush();
stringStream.Position = 0;
- return (Stream)stringStream;
+ return new ResultInfo<Stream>((Stream)stringStream, true);
});
}
- public static Task<string> ReadAllTextAsync(
+ public static async Task<ResultInfo<string>> ReadAllTextAsync(
this OneOf<string, FileInfo> input,
IFileStorage fileStorage,
CancellationToken cancellationToken)
{
if (input.IsT1)
{
- return ReadAllTextAsync(OneOf<FileInfo, string>.FromT0(input.AsT1), fileStorage, cancellationToken);
+ return await ReadAllTextAsync(OneOf<FileInfo, string>.FromT0(input.AsT1), fileStorage, cancellationToken);
}
- return ReadAllTextAsync(OneOf<FileInfo, string>.FromT1(input.AsT0), fileStorage, cancellationToken);
+ return await ReadAllTextAsync(OneOf<FileInfo, string>.FromT1(input.AsT0), fileStorage, cancellationToken);
}
- public static Task<string> ReadAllTextAsync(
+ public static async Task<ResultInfo<string>> ReadAllTextAsync(
this OneOf<FileInfo, string> input,
IFileStorage fileStorage,
CancellationToken cancellationToken)
{
- return
- input.Match(
- async inputFile =>
+ return await input.Match(
+ async inputFile =>
+ {
+ if (!fileStorage.FileExists(inputFile.FullName))
{
- using Stream fileStream = fileStorage.OpenReadFile(inputFile.FullName);
- using var reader = new StreamReader(fileStream);
- string content = await reader.ReadToEndAsync(cancellationToken);
- return content;
- },
- inputString => Task.FromResult(inputString));
+ return new ResultInfo<string>("", false);
+ }
+
+ using Stream fileStream = fileStorage.OpenReadFile(inputFile.FullName);
+ using var reader = new StreamReader(fileStream);
+ string content = await reader.ReadToEndAsync(cancellationToken);
+ return new ResultInfo<string>(content, true);
+ },
+ inputString => Task.FromResult(new ResultInfo<string>(inputString, true)));
}
}
diff --git a/src/app/dev/DevToys.Api/Core/ResultInfo.cs b/src/app/dev/DevToys.Api/Core/ResultInfo.cs
new file mode 100644
index 000000000..779b3b38f
--- /dev/null
+++ b/src/app/dev/DevToys.Api/Core/ResultInfo.cs
@@ -0,0 +1,9 @@
+namespace DevToys.Api;
+
+/// <summary>
+/// Record to contain both whether the task was a success and the resulting data
+/// </summary>
+/// <typeparam name="T">Type of the result</typeparam>
+/// <param name="Data">The resulting data or the task</param>
+/// <param name="HasSucceeded">Whether the task succeeded</param>
+public record ResultInfo<T>(T Data, bool HasSucceeded = true);
diff --git a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs
index e6cca2a32..5aa343074 100644
--- a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs
+++ b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs
@@ -4,6 +4,7 @@ public static class PredefinedCommonToolGroupNames
{
public const string EncodersDecoders = "Encoders / Decoders";
public const string Converters = "Converters";
+ public const string Formatters = "Formatters";
public const string Generators = "Generators";
public const string Graphic = "Graphic";
public const string Text = "Text";
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
index 22ee6e574..99f558284 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
@@ -6,6 +6,7 @@ public static class PredefinedCommonDataTypeNames
public const string Json = "json";
public const string JsonArray = "jsonArray";
public const string Yaml = "yaml";
+ public const string Xml = "xml";
public const string Base64Text = "base64Text";
public const string Base64Image = "base64Image";
public const string Image = "image";
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
index a7b32d40f..eb0f6f4af 100644
--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
@@ -38,6 +38,16 @@
<AutoGen>True</AutoGen>
<DependentUpon>GlobalStrings.resx</DependentUpon>
</Compile>
+ <Compile Update="Tools\Formatters\Xml\XmlFormatter.Designer.cs">
+ <DependentUpon>XmlFormatter.resx</DependentUpon>
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ </Compile>
+ <Compile Update="Tools\Formatters\Formatters.Designer.cs">
+ <DependentUpon>Formatters.resx</DependentUpon>
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ </Compile>
<Compile Update="Tools\Converters\JsonTable\JsonTableConverter.Designer.cs">
<DependentUpon>JsonTableConverter.resx</DependentUpon>
<DesignTime>True</DesignTime>
@@ -158,6 +168,14 @@
<LastGenOutput>JsonTableConverter.Designer.cs</LastGenOutput>
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
+ <EmbeddedResource Update="Tools\Formatters\Xml\XmlFormatter.resx">
+ <LastGenOutput>XmlFormatter.Designer.cs</LastGenOutput>
+ <Generator>ResXFileCodeGenerator</Generator>
+ </EmbeddedResource>
+ <EmbeddedResource Update="Tools\Formatters\Formatters.resx">
+ <LastGenOutput>Formatters.Designer.cs</LastGenOutput>
+ <Generator>ResXFileCodeGenerator</Generator>
+ </EmbeddedResource>
<EmbeddedResource Update="Tools\EncodersDecoders\Base64Image\Base64ImageEncoderDecoder.resx">
<LastGenOutput>Base64ImageEncoderDecoder.Designer.cs</LastGenOutput>
<Generator>ResXFileCodeGenerator</Generator>
diff --git a/src/app/dev/DevToys.Tools/Helpers/FileHelper.cs b/src/app/dev/DevToys.Tools/Helpers/FileHelper.cs
new file mode 100644
index 000000000..ca1ff4a84
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/FileHelper.cs
@@ -0,0 +1,18 @@
+namespace DevToys.Tools.Helpers;
+internal static class FileHelper
+{
+ /// <summary>
+ /// Writes the output to the output file path if provided, otherwise to the console
+ /// </summary>
+ internal static async Task WriteOutputAsync(string output, FileInfo? outputFile, CancellationToken cancellationToken)
+ {
+ if (outputFile is null)
+ {
+ Console.WriteLine(output);
+ }
+ else
+ {
+ await File.WriteAllTextAsync(outputFile.FullName, output, cancellationToken);
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs
index 27beb23b6..ab27d50d5 100644
--- a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs
+++ b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs
@@ -140,7 +140,7 @@ internal static partial class JsonHelper
/// <summary>
/// Convert a Yaml string to Json
/// </summary>
- internal static ToolResult<string> ConvertFromYaml(
+ internal static ResultInfo<string> ConvertFromYaml(
string? input,
Indentation indentationMode,
ILogger logger,
diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs
index e38bd7578..40d45e921 100644
--- a/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs
+++ b/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs
@@ -6,7 +6,7 @@ namespace DevToys.Tools.Helpers;
internal static class JsonYamlHelper
{
- public static async ValueTask<ToolResult<string>> ConvertAsync(
+ public static async ValueTask<ResultInfo<string>> ConvertAsync(
string input,
JsonToYamlConversion conversion,
Indentation indentation,
@@ -15,7 +15,7 @@ internal static class JsonYamlHelper
{
await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
- ToolResult<string> conversionResult;
+ ResultInfo<string> conversionResult;
switch (conversion)
{
case JsonToYamlConversion.JsonToYaml:
diff --git a/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs
new file mode 100644
index 000000000..c4aa3f743
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs
@@ -0,0 +1,157 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Xml;
+using DevToys.Tools.Models;
+using Markdig.Helpers;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Helpers;
+
+internal static class XmlHelper
+{
+ /// <summary>
+ /// Detects whether the given string is a valid Xml or not.
+ /// </summary>
+ internal static bool IsValid(string? input, ILogger logger)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ return false;
+ }
+
+ if (!ValidateFirstAndLastCharOfXml(input))
+ {
+ return false;
+ }
+
+ try
+ {
+ var xmlDocument = new XmlDocument();
+
+ // If loading failed, it's not valid Xml.
+ xmlDocument.LoadXml(input);
+
+ return true;
+ }
+ catch (XmlException)
+ {
+ return false;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Invalid data detected 'input'", input);
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Format a string to the specified Xml format.
+ /// </summary>
+ internal static ResultInfo<string> Format(string? input, Indentation indentationMode, bool newLineOnAttributes, ILogger logger)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ return new(string.Empty, false);
+ }
+
+ try
+ {
+ var xmlDocument = new XmlDocument();
+ xmlDocument.LoadXml(input);
+
+ if (xmlDocument.FirstChild == null)
+ {
+ return new(string.Empty, false);
+ }
+
+ var xmlWriterSettings = new XmlWriterSettings()
+ {
+ Async = true,
+ OmitXmlDeclaration = xmlDocument.FirstChild.NodeType != XmlNodeType.XmlDeclaration,
+ NewLineOnAttributes = newLineOnAttributes,
+ };
+
+ switch (indentationMode)
+ {
+ case Indentation.TwoSpaces:
+ xmlWriterSettings.Indent = true;
+ xmlWriterSettings.IndentChars = " ";
+ break;
+ case Indentation.FourSpaces:
+ xmlWriterSettings.Indent = true;
+ xmlWriterSettings.IndentChars = " ";
+ break;
+ case Indentation.OneTab:
+ xmlWriterSettings.Indent = true;
+ xmlWriterSettings.IndentChars = "\t";
+ break;
+ case Indentation.Minified:
+ xmlWriterSettings.Indent = false;
+ break;
+ default:
+ throw new NotSupportedException();
+ }
+
+ var stringBuilder = new StringBuilder();
+ using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
+ {
+ xmlDocument.Save(xmlWriter);
+ }
+
+ if (xmlDocument.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
+ {
+ Match match = Regex.Match(xmlDocument.FirstChild.InnerText, @"(?<=encoding\s*=\s*"")[^""]*", RegexOptions.None);
+ if (match.Success)
+ {
+ stringBuilder = stringBuilder.Replace("utf-16", match.Value);
+ }
+ else
+ {
+ stringBuilder = stringBuilder.Replace("encoding=\"utf-16\"", "");
+ }
+ }
+ return new(stringBuilder.ToString());
+ }
+ catch (XmlException ex)
+ {
+ return new(ex.Message, false);
+ }
+ catch (Exception ex) // some other exception
+ {
+ logger.LogError(ex, "Xml formatter", $"Indentation: {indentationMode}");
+ return new(ex.Message, false);
+ }
+ }
+
+ /// <summary>
+ /// Validate that the XML starts with "<" and ends with ">", ignoring whitespace
+ /// </summary>
+ private static bool ValidateFirstAndLastCharOfXml(string input)
+ {
+ for (int i = 0; i < input.Length; ++i)
+ {
+ if (!input[i].IsWhitespace())
+ {
+ if (input[i] == '<')
+ {
+ break;
+ }
+ return false;
+ }
+ }
+
+ for (int i = input.Length - 1; i >= 0; --i)
+ {
+ if (!input[i].IsWhitespace())
+ {
+ if (input[i] == '>')
+ {
+ return true;
+ }
+ return false;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs
index f17516c9e..3eff0d785 100644
--- a/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs
+++ b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs
@@ -50,7 +50,7 @@ internal static partial class YamlHelper
/// <summary>
/// Convert a Json string to Yaml
/// </summary>
- internal static ToolResult<string> ConvertFromJson(
+ internal static ResultInfo<string> ConvertFromJson(
string? input,
Indentation indentation,
ILogger logger,
diff --git a/src/app/dev/DevToys.Tools/Models/ToolResult.cs b/src/app/dev/DevToys.Tools/Models/ToolResult.cs
deleted file mode 100644
index 4d5909a57..000000000
--- a/src/app/dev/DevToys.Tools/Models/ToolResult.cs
+++ /dev/null
@@ -1,3 +0,0 @@
-namespace DevToys.Tools.Models;
-
-internal record ToolResult<T>(T Data, bool HasSucceeded = true);
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/JsonArrayDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/JsonArrayDataTypeDetector.cs
index 3e0ce26ad..cec2aab60 100644
--- a/src/app/dev/DevToys.Tools/SmartDetection/JsonArrayDataTypeDetector.cs
+++ b/src/app/dev/DevToys.Tools/SmartDetection/JsonArrayDataTypeDetector.cs
@@ -46,7 +46,4 @@ internal sealed partial class JsonArrayDataTypeDetector : IDataTypeDetector
return false;
}
}
-
- [LoggerMessage(1, LogLevel.Error, "An unexpected exception happened while trying to detect some JSON Array data.")]
- partial void LogError(Exception ex);
}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs
index a332372aa..30980c51a 100644
--- a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs
+++ b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs
@@ -32,7 +32,4 @@ internal sealed partial class JsonDataTypeDetector : IDataTypeDetector
return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
}
-
- [LoggerMessage(1, LogLevel.Error, "An unexpected exception happened while trying to detect some JSON data.")]
- partial void LogError(Exception ex);
}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/XmlDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/XmlDataTypeDetector.cs
new file mode 100644
index 000000000..55a6632c8
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/XmlDataTypeDetector.cs
@@ -0,0 +1,34 @@
+using DevToys.Tools.Helpers;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Xml, baseName: PredefinedCommonDataTypeNames.Text)]
+internal sealed partial class XmlDataTypeDetector : IDataTypeDetector
+{
+ private readonly ILogger _logger;
+
+ [ImportingConstructor]
+ public XmlDataTypeDetector()
+ {
+ _logger = this.Log();
+ }
+
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(
+ object data,
+ DataDetectionResult? resultFromBaseDetector,
+ CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is string dataString)
+ {
+ if (XmlHelper.IsValid(dataString, _logger))
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs
index d2372d257..e7cb37fd8 100644
--- a/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs
+++ b/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs
@@ -31,7 +31,4 @@ internal sealed partial class YamlDataTypeDetector : IDataTypeDetector
return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
}
-
- [LoggerMessage(1, LogLevel.Error, "An unexpected exception happened while trying to detect some JSON data.")]
- partial void LogError(Exception ex);
}
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs
index 41e4a68ed..6a3d13f8b 100644
--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs
@@ -133,7 +133,7 @@ namespace DevToys.Tools.Tools.Converters.JsonYaml {
}
/// <summary>
- /// Looks up a localized string similar to Select which indentation do you want to use.
+ /// Looks up a localized string similar to Select which indentation you want to use.
/// </summary>
internal static string IndentationOptionDescription {
get {
@@ -169,7 +169,7 @@ namespace DevToys.Tools.Tools.Converters.JsonYaml {
}
/// <summary>
- /// Looks up a localized string similar to Please specify an input text or a input file.
+ /// Looks up a localized string similar to Please specify an input text or an input file.
/// </summary>
internal static string InvalidInputOrFileCommand {
get {
@@ -223,7 +223,7 @@ namespace DevToys.Tools.Tools.Converters.JsonYaml {
}
/// <summary>
- /// Looks up a localized string similar to File where the result should be persisted..
+ /// Looks up a localized string similar to Path to the output file.
/// </summary>
internal static string OutputFileOptionDescription {
get {
@@ -231,15 +231,6 @@ namespace DevToys.Tools.Tools.Converters.JsonYaml {
}
}
- /// <summary>
- /// Looks up a localized string similar to JSON &lt;&gt; YAML Converter.
- /// </summary>
- internal static string SearchDisplayName {
- get {
- return ResourceManager.GetString("SearchDisplayName", resourceCulture);
- }
- }
-
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx
index cd603fc3b..51e0fbf24 100644
--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx
@@ -142,7 +142,7 @@
<value>Indentation</value>
</data>
<data name="IndentationOptionDescription" xml:space="preserve">
- <value>Select which indentation do you want to use</value>
+ <value>Select which indentation you want to use</value>
</data>
<data name="Input" xml:space="preserve">
<value>Input</value>
@@ -154,7 +154,7 @@
<value>Text or path to a file to convert from json or yaml</value>
</data>
<data name="InvalidInputOrFileCommand" xml:space="preserve">
- <value>Please specify an input text or a input file</value>
+ <value>Please specify an input text or an input file</value>
</data>
<data name="InvalidJson" xml:space="preserve">
<value>&lt;Invalid JSON data&gt;</value>
@@ -172,10 +172,7 @@
<value>Output</value>
</data>
<data name="OutputFileOptionDescription" xml:space="preserve">
- <value>File where the result should be persisted.</value>
- </data>
- <data name="SearchDisplayName" xml:space="preserve">
- <value>JSON &lt;&gt; YAML Converter</value>
+ <value>Path to the output file</value>
</data>
<data name="SearchKeywords" xml:space="preserve">
<value />
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs
index 9282e8be4..6678d636d 100644
--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs
@@ -13,6 +13,10 @@ namespace DevToys.Tools.Tools.Converters.JsonYaml;
DescriptionResourceName = nameof(JsonYamlConverter.Description))]
internal sealed class JsonYamlConverterCommandLineTool : ICommandLineTool
{
+#pragma warning disable IDE0044 // Add readonly modifier
+ [Import]
+ private IFileStorage _fileStorage = null!;
+#pragma warning restore IDE0044 // Add readonly modifier
[CommandLineOption(
Name = "input",
Alias = "i",
@@ -38,33 +42,24 @@ internal sealed class JsonYamlConverterCommandLineTool : ICommandLineTool
DescriptionResourceName = nameof(JsonYamlConverter.IndentationOptionDescription))]
internal Indentation IndentationMode { get; set; } = Indentation.TwoSpaces;
- public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
{
if (!Input.HasValue)
{
Console.Error.WriteLine(JsonYamlConverter.InvalidInputOrFileCommand);
- return ValueTask.FromResult(-1);
+ return -1;
}
- return Input.Value.Match(
- file =>
- InvokeFileAsync(
- file,
- logger,
- cancellationToken),
- text =>
- InvokeCliAsync(
- text,
- logger,
- cancellationToken));
- }
-
- private async ValueTask<int> InvokeCliAsync(string input, ILogger logger, CancellationToken cancellationToken)
- {
- Guard.IsNotNull(Input);
+ ResultInfo<string> input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!input.HasSucceeded)
+ {
+ Console.Error.WriteLine(JsonYamlConverter.InputFileNotFound);
+ return -1;
+ }
- ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(
- input,
+ Guard.IsNotNull(input.Data);
+ ResultInfo<string> conversionResult = await JsonYamlHelper.ConvertAsync(
+ input.Data,
ConversionMode,
IndentationMode,
logger,
@@ -79,37 +74,7 @@ internal sealed class JsonYamlConverterCommandLineTool : ICommandLineTool
return -1;
}
- Console.WriteLine(conversionResult.Data);
- return 0;
- }
-
- private async ValueTask<int> InvokeFileAsync(FileInfo file, ILogger logger, CancellationToken cancellationToken)
- {
- Guard.IsNotNull(OutputFile);
-
- if (!file.Exists)
- {
- Console.Error.WriteLine(JsonYamlConverter.InputFileNotFound);
- return -1;
- }
-
- string content = await File.ReadAllTextAsync(file.FullName, cancellationToken);
-
- ToolResult<string> conversionResult
- = await JsonYamlHelper.ConvertAsync(
- content!,
- ConversionMode,
- IndentationMode,
- logger,
- cancellationToken);
-
- if (!conversionResult.HasSucceeded)
- {
- Console.Error.WriteLine(conversionResult.Data);
- return -1;
- }
-
- await File.WriteAllTextAsync(OutputFile.FullName, conversionResult.Data, cancellationToken);
+ await FileHelper.WriteOutputAsync(conversionResult.Data, OutputFile, cancellationToken);
return 0;
}
}
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
index 3573cdfd3..fc72775f9 100644
--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
@@ -208,7 +208,7 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable
{
await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
- ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(
+ ResultInfo<string> conversionResult = await JsonYamlHelper.ConvertAsync(
input,
_settingsProvider.GetSetting(conversionMode),
_settingsProvider.GetSetting(indentationMode),
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.Designer.cs
index 686b33155..3bb8714dd 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.Designer.cs
@@ -106,7 +106,7 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Image {
}
/// <summary>
- /// Looks up a localized string similar to File where the result should be persisted..
+ /// Looks up a localized string similar to Path to the output file.
/// </summary>
internal static string OutputFileOptionDescription {
get {
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.resx
index 179f7b367..42b108ea7 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.resx
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoder.resx
@@ -133,7 +133,7 @@
<value>Base64 Image Encoder / Decoder</value>
</data>
<data name="OutputFileOptionDescription" xml:space="preserve">
- <value>File where the result should be persisted.</value>
+ <value>Path to the output file</value>
</data>
<data name="SearchKeywords" xml:space="preserve">
<value>RFC 4648</value>
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs
index b9c6f7306..3455614e8 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs
@@ -1,4 +1,5 @@
-using DevToys.Tools.SmartDetection;
+using DevToys.Tools.Helpers;
+using DevToys.Tools.SmartDetection;
using DevToys.Tools.Strings.GlobalStrings;
using Microsoft.Extensions.Logging;
using OneOf;
@@ -94,14 +95,7 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : IComman
_ => throw new NotSupportedException(),
};
- if (OutputFile is null)
- {
- Console.WriteLine(output);
- }
- else
- {
- await File.WriteAllTextAsync(OutputFile.FullName, output, cancellationToken);
- }
+ await FileHelper.WriteOutputAsync(output, OutputFile, cancellationToken);
}
private async ValueTask<int> DecodeAsync(string input, CancellationToken cancellationToken)
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs
index 242a5f2b4..33c0f1e09 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs
@@ -142,7 +142,7 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text {
}
/// <summary>
- /// Looks up a localized string similar to Select which encoding do you want to use.
+ /// Looks up a localized string similar to Select which encoding you want to use.
/// </summary>
internal static string EncodingDescription {
get {
@@ -168,6 +168,15 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Input file selected doesn&apos;t exist.
+ /// </summary>
+ internal static string InputFileNotFound {
+ get {
+ return ResourceManager.GetString("InputFileNotFound", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Text or path to a file to encode or Base64 to decode.
/// </summary>
@@ -195,6 +204,15 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input text or an input file.
+ /// </summary>
+ internal static string InvalidInputOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Base64 Text Encoder / Decoder.
/// </summary>
@@ -205,7 +223,7 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text {
}
/// <summary>
- /// Looks up a localized string similar to File where the result should be persisted..
+ /// Looks up a localized string similar to Path to the output file.
/// </summary>
internal static string OutputFileOptionDescription {
get {
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
index 194566eeb..13b27e479 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
@@ -145,7 +145,7 @@
<value>Encode and decode Base64 text data</value>
</data>
<data name="EncodingDescription" xml:space="preserve">
- <value>Select which encoding do you want to use</value>
+ <value>Select which encoding you want to use</value>
</data>
<data name="EncodingOptionDescription" xml:space="preserve">
<value>Encoding</value>
@@ -153,6 +153,9 @@
<data name="EncodingTitle" xml:space="preserve">
<value>Encoding</value>
</data>
+ <data name="InputFileNotFound" xml:space="preserve">
+ <value>Input file selected doesn't exist</value>
+ </data>
<data name="InputOptionDescription" xml:space="preserve">
<value>Text or path to a file to encode or Base64 to decode</value>
</data>
@@ -162,11 +165,14 @@
<data name="InvalidBase64" xml:space="preserve">
<value>&lt;Invalid Base64&gt;</value>
</data>
+ <data name="InvalidInputOrFileCommand" xml:space="preserve">
+ <value>Please specify an input text or an input file</value>
+ </data>
<data name="LongDisplayTitle" xml:space="preserve">
<value>Base64 Text Encoder / Decoder</value>
</data>
<data name="OutputFileOptionDescription" xml:space="preserve">
- <value>File where the result should be persisted.</value>
+ <value>Path to the output file</value>
</data>
<data name="OutputTitle" xml:space="preserve">
<value>Output</value>
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs
index 8ea39e35d..b6f3e71d3 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs
@@ -1,5 +1,4 @@
-using DevToys.Api.Core;
-using DevToys.Tools.Helpers;
+using DevToys.Tools.Helpers;
using DevToys.Tools.Models;
using Microsoft.Extensions.Logging;
using OneOf;
@@ -47,31 +46,38 @@ internal sealed class Base64TextEncoderDecoderCommandLineTool : ICommandLineTool
public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
{
- string? input = null;
+ ResultInfo<string> result;
+ if (!Input.HasValue)
+ {
+ Console.Error.WriteLine(Base64TextEncoderDecoder.InvalidInputOrFileCommand);
+ return -1;
+ }
- if (Input.HasValue)
+ result = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!result.HasSucceeded)
{
- input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ Console.Error.WriteLine(Base64TextEncoderDecoder.InputFileNotFound);
+ return -1;
}
- Guard.IsNotNull(input);
+ Guard.IsNotNull(result.Data);
string output;
switch (EncodingConversionMode)
{
case EncodingConversion.Encode:
- output = Base64Helper.FromTextToBase64(input, EncodingMode, logger, cancellationToken);
+ output = Base64Helper.FromTextToBase64(result.Data, EncodingMode, logger, cancellationToken);
break;
case EncodingConversion.Decode:
- if (!Base64Helper.IsBase64DataStrict(input))
+ if (!Base64Helper.IsBase64DataStrict(result.Data))
{
cancellationToken.ThrowIfCancellationRequested();
Console.Error.WriteLine(Base64TextEncoderDecoder.InvalidBase64);
return -1;
}
- output = Base64Helper.FromBase64ToText(input, EncodingMode, logger, cancellationToken);
+ output = Base64Helper.FromBase64ToText(result.Data, EncodingMode, logger, cancellationToken);
break;
default:
@@ -80,15 +86,7 @@ internal sealed class Base64TextEncoderDecoderCommandLineTool : ICommandLineTool
cancellationToken.ThrowIfCancellationRequested();
- if (OutputFile is null)
- {
- Console.WriteLine(output);
- }
- else
- {
- await File.WriteAllTextAsync(OutputFile.FullName, output, cancellationToken);
- }
-
+ await FileHelper.WriteOutputAsync(output, OutputFile, cancellationToken);
return 0;
}
}
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.Designer.cs
new file mode 100644
index 000000000..e8b90d66b
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.Designer.cs
@@ -0,0 +1,81 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DevToys.Tools.Tools.Formatters {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Formatters {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Formatters() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Formatters.Formatters", typeof(Formatters).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Formatters.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Formatters.
+ /// </summary>
+ internal static string DisplayTitle {
+ get {
+ return ResourceManager.GetString("DisplayTitle", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.resx b/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.resx
new file mode 100644
index 000000000..dbce062fd
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Formatters.resx
@@ -0,0 +1,126 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AccessibleName" xml:space="preserve">
+ <value>Formatters</value>
+ </data>
+ <data name="DisplayTitle" xml:space="preserve">
+ <value>Formatters</value>
+ </data>
+</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/FormattersGroup.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/FormattersGroup.cs
new file mode 100644
index 000000000..ed40fa2e6
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/FormattersGroup.cs
@@ -0,0 +1,15 @@
+namespace DevToys.Tools.Tools.Formatters;
+
+[Export(typeof(GuiToolGroup))]
+[Name(PredefinedCommonToolGroupNames.Formatters)]
+internal class FormattersGroup : GuiToolGroup
+{
+ [ImportingConstructor]
+ internal FormattersGroup()
+ {
+ IconFontName = "DevToys-Tools-Icons";
+ IconGlyph = '\u0123';
+ DisplayTitle = Formatters.DisplayTitle;
+ AccessibleName = Formatters.AccessibleName;
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.Designer.cs
new file mode 100644
index 000000000..525a70d5a
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.Designer.cs
@@ -0,0 +1,243 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DevToys.Tools.Tools.Formatters.Xml {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class XmlFormatter {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal XmlFormatter() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Formatters.Xml.XmlFormatter", typeof(XmlFormatter).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML Formatter tool.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Configuration.
+ /// </summary>
+ internal static string Configuration {
+ get {
+ return ResourceManager.GetString("Configuration", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Indent or minify XML data.
+ /// </summary>
+ internal static string Description {
+ get {
+ return ResourceManager.GetString("Description", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to 4 spaces.
+ /// </summary>
+ internal static string FourSpaces {
+ get {
+ return ResourceManager.GetString("FourSpaces", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Indentation.
+ /// </summary>
+ internal static string Indentation {
+ get {
+ return ResourceManager.GetString("Indentation", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Select which indentation you want to use.
+ /// </summary>
+ internal static string IndentationOptionDescription {
+ get {
+ return ResourceManager.GetString("IndentationOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Input.
+ /// </summary>
+ internal static string Input {
+ get {
+ return ResourceManager.GetString("Input", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Input file selected doesn&apos;t exist..
+ /// </summary>
+ internal static string InputFileNotFound {
+ get {
+ return ResourceManager.GetString("InputFileNotFound", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text or path to a file containing the xml to format.
+ /// </summary>
+ internal static string InputOptionDescription {
+ get {
+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input text or an input file.
+ /// </summary>
+ internal static string InvalidInputOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML Formatter.
+ /// </summary>
+ internal static string LongDisplayTitle {
+ get {
+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Minified.
+ /// </summary>
+ internal static string Minified {
+ get {
+ return ResourceManager.GetString("Minified", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to New Line on Attributes.
+ /// </summary>
+ internal static string NewLineOnAttributes {
+ get {
+ return ResourceManager.GetString("NewLineOnAttributes", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Whether to put attributes on a new line.
+ /// </summary>
+ internal static string NewLineOnAttributesDescription {
+ get {
+ return ResourceManager.GetString("NewLineOnAttributesDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to 1 tab.
+ /// </summary>
+ internal static string OneTab {
+ get {
+ return ResourceManager.GetString("OneTab", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Output.
+ /// </summary>
+ internal static string Output {
+ get {
+ return ResourceManager.GetString("Output", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Path to the output file.
+ /// </summary>
+ internal static string OutputFileOptionDescription {
+ get {
+ return ResourceManager.GetString("OutputFileOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML Formatter.
+ /// </summary>
+ internal static string SearchDisplayName {
+ get {
+ return ResourceManager.GetString("SearchDisplayName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML.
+ /// </summary>
+ internal static string ShortDisplayTitle {
+ get {
+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to 2 spaces.
+ /// </summary>
+ internal static string TwoSpaces {
+ get {
+ return ResourceManager.GetString("TwoSpaces", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.resx b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.resx
new file mode 100644
index 000000000..5c2846bf0
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatter.resx
@@ -0,0 +1,180 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AccessibleName" xml:space="preserve">
+ <value>XML Formatter tool</value>
+ </data>
+ <data name="Configuration" xml:space="preserve">
+ <value>Configuration</value>
+ </data>
+ <data name="Description" xml:space="preserve">
+ <value>Indent or minify XML data</value>
+ </data>
+ <data name="FourSpaces" xml:space="preserve">
+ <value>4 spaces</value>
+ </data>
+ <data name="Indentation" xml:space="preserve">
+ <value>Indentation</value>
+ </data>
+ <data name="IndentationOptionDescription" xml:space="preserve">
+ <value>Select which indentation you want to use</value>
+ </data>
+ <data name="Input" xml:space="preserve">
+ <value>Input</value>
+ </data>
+ <data name="InputFileNotFound" xml:space="preserve">
+ <value>Input file selected doesn't exist.</value>
+ </data>
+ <data name="InputOptionDescription" xml:space="preserve">
+ <value>Text or path to a file containing the xml to format</value>
+ </data>
+ <data name="InvalidInputOrFileCommand" xml:space="preserve">
+ <value>Please specify an input text or an input file</value>
+ </data>
+ <data name="LongDisplayTitle" xml:space="preserve">
+ <value>XML Formatter</value>
+ </data>
+ <data name="Minified" xml:space="preserve">
+ <value>Minified</value>
+ </data>
+ <data name="NewLineOnAttributes" xml:space="preserve">
+ <value>New Line on Attributes</value>
+ </data>
+ <data name="NewLineOnAttributesDescription" xml:space="preserve">
+ <value>Whether to put attributes on a new line</value>
+ </data>
+ <data name="OneTab" xml:space="preserve">
+ <value>1 tab</value>
+ </data>
+ <data name="Output" xml:space="preserve">
+ <value>Output</value>
+ </data>
+ <data name="OutputFileOptionDescription" xml:space="preserve">
+ <value>Path to the output file</value>
+ </data>
+ <data name="SearchDisplayName" xml:space="preserve">
+ <value>XML Formatter</value>
+ </data>
+ <data name="ShortDisplayTitle" xml:space="preserve">
+ <value>XML</value>
+ </data>
+ <data name="TwoSpaces" xml:space="preserve">
+ <value>2 spaces</value>
+ </data>
+</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterCommandLineTool.cs
new file mode 100644
index 000000000..b9871a3f2
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterCommandLineTool.cs
@@ -0,0 +1,78 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+using OneOf;
+
+namespace DevToys.Tools.Tools.Formatters.Xml;
+
+[Export(typeof(ICommandLineTool))]
+[Name("XmlFormatter")]
+[CommandName(
+ Name = "xmlFormatter",
+ Alias = "xmlf",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Formatters.Xml.XmlFormatter",
+ DescriptionResourceName = nameof(XmlFormatter.Description))]
+internal sealed class XmlFormatterCommandLineTool : ICommandLineTool
+{
+#pragma warning disable IDE0044 // Add readonly modifier
+ [Import]
+ private IFileStorage _fileStorage = null!;
+#pragma warning restore IDE0044 // Add readonly modifier
+
+ [CommandLineOption(
+ Name = "input",
+ Alias = "i",
+ IsRequired = true,
+ DescriptionResourceName = nameof(XmlFormatter.InputOptionDescription))]
+ internal OneOf<FileInfo, string>? Input { get; set; }
+
+ [CommandLineOption(
+ Name = "outputFile",
+ Alias = "o",
+ DescriptionResourceName = nameof(XmlFormatter.OutputFileOptionDescription))]
+ internal FileInfo? OutputFile { get; set; }
+
+ [CommandLineOption(
+ Name = "indentation",
+ DescriptionResourceName = nameof(XmlFormatter.IndentationOptionDescription))]
+ internal Indentation IndentationMode { get; set; } = Indentation.TwoSpaces;
+
+ [CommandLineOption(
+ Name = "newLineOnAttributes",
+ DescriptionResourceName = nameof(XmlFormatter.NewLineOnAttributesDescription))]
+ internal bool NewLineOnAttributes { get; set; } = false;
+
+ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ {
+ if (!Input.HasValue)
+ {
+ Console.Error.WriteLine(XmlFormatter.InvalidInputOrFileCommand);
+ return -1;
+ }
+
+ ResultInfo<string> input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!input.HasSucceeded)
+ {
+ Console.Error.WriteLine(XmlFormatter.InputFileNotFound);
+ return -1;
+ }
+
+ Guard.IsNotNull(input.Data);
+ ResultInfo<string> formatResult = XmlHelper.Format(
+ input.Data,
+ IndentationMode,
+ NewLineOnAttributes,
+ logger);
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (!formatResult.HasSucceeded)
+ {
+ Console.Error.WriteLine(formatResult.Data);
+ return -1;
+ }
+
+ await FileHelper.WriteOutputAsync(formatResult.Data, OutputFile, cancellationToken);
+ return 0;
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs
new file mode 100644
index 000000000..beb89195a
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs
@@ -0,0 +1,183 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Tools.Formatters.Xml;
+
+[Export(typeof(IGuiTool))]
+[Name("XmlFormatter")]
+[ToolDisplayInformation(
+ IconFontName = "DevToys-Tools-Icons",
+ IconGlyph = '\u0122',
+ GroupName = PredefinedCommonToolGroupNames.Formatters,
+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Formatters.Xml.XmlFormatter",
+ ShortDisplayTitleResourceName = nameof(XmlFormatter.ShortDisplayTitle),
+ LongDisplayTitleResourceName = nameof(XmlFormatter.LongDisplayTitle),
+ DescriptionResourceName = nameof(XmlFormatter.Description),
+ AccessibleNameResourceName = nameof(XmlFormatter.AccessibleName))]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xml)]
+internal sealed partial class XmlFormatterGuiTool : IGuiTool, IDisposable
+{
+ private const string XmlLanguage = "xml";
+
+ /// <summary>
+ /// Which indentation the tool need to use.
+ /// </summary>
+ private static readonly SettingDefinition<Indentation> indentationMode
+ = new(name: $"{nameof(XmlFormatterGuiTool)}.{nameof(indentationMode)}", defaultValue: Indentation.TwoSpaces);
+
+ /// <summary>
+ /// Whether XML attributes are put on a new line
+ /// </summary>
+ private static readonly SettingDefinition<bool> newLineOnAttributes
+ = new(name: $"{nameof(XmlFormatterGuiTool)}.{nameof(newLineOnAttributes)}", defaultValue: false);
+
+ private enum GridColumn
+ {
+ Content
+ }
+
+ private enum GridRow
+ {
+ Header,
+ Content,
+ Footer
+ }
+
+ private readonly DisposableSemaphore _semaphore = new();
+ private readonly ILogger _logger;
+ private readonly ISettingsProvider _settingsProvider;
+ private readonly IUIMultiLineTextInput _inputTextArea = MultilineTextInput("xml-input-text-area");
+ private readonly IUIMultiLineTextInput _outputTextArea = MultilineTextInput("xml-output-text-area");
+
+ private CancellationTokenSource? _cancellationTokenSource;
+
+ [ImportingConstructor]
+ public XmlFormatterGuiTool(ISettingsProvider settingsProvider)
+ {
+ _logger = this.Log();
+ _settingsProvider = settingsProvider;
+ }
+
+ internal Task? WorkTask { get; private set; }
+
+ public UIToolView View
+ => new(
+ isScrollable: true,
+ Grid()
+ .ColumnLargeSpacing()
+ .RowLargeSpacing()
+ .Rows(
+ (GridRow.Header, Auto),
+ (GridRow.Content, new UIGridLength(1, UIGridUnitType.Fraction))
+ )
+ .Columns(
+ (GridColumn.Content, new UIGridLength(1, UIGridUnitType.Fraction))
+ )
+ .Cells(
+ Cell(
+ GridRow.Header,
+ GridColumn.Content,
+ Stack().Vertical().WithChildren(
+ Label().Text(XmlFormatter.Configuration),
+ Setting("xml-text-indentation-setting")
+ .Icon("FluentSystemIcons", '\uF6F8')
+ .Title(XmlFormatter.Indentation)
+ .Handle(
+ _settingsProvider,
+ indentationMode,
+ OnIndentationModelChanged,
+ Item(XmlFormatter.TwoSpaces, Indentation.TwoSpaces),
+ Item(XmlFormatter.FourSpaces, Indentation.FourSpaces),
+ Item(XmlFormatter.OneTab, Indentation.OneTab),
+ Item(XmlFormatter.Minified, Indentation.Minified)
+ ),
+ Setting("xml-text-newLineOnAttributes-setting")
+ .Icon("FluentSystemIcons", '\uf7ed')
+ .Title(XmlFormatter.NewLineOnAttributes)
+ .Description(XmlFormatter.NewLineOnAttributesDescription)
+ .Handle(
+ _settingsProvider,
+ newLineOnAttributes,
+ OnSettingChanged
+ )
+ )
+ ),
+ Cell(
+ GridRow.Content,
+ GridColumn.Content,
+ SplitGrid()
+ .Vertical()
+ .WithLeftPaneChild(
+ _inputTextArea
+ .Title(XmlFormatter.Input)
+ .OnTextChanged(OnInputTextChanged))
+ .WithRightPaneChild(
+ _outputTextArea
+ .Title(XmlFormatter.Output)
+ .ReadOnly()
+ .Extendable())
+ )
+ )
+ );
+
+ // Smart detection handler.
+ public void OnDataReceived(string dataTypeName, object? parsedData)
+ {
+ if (dataTypeName == PredefinedCommonDataTypeNames.Xml &&
+ parsedData is string xmlStrongTypedParsedData)
+ {
+ _inputTextArea.Language(XmlLanguage);
+ _outputTextArea.Language(XmlLanguage);
+ _inputTextArea.Text(xmlStrongTypedParsedData);
+ }
+ }
+
+ public void Dispose()
+ {
+ _cancellationTokenSource?.Cancel();
+ _cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
+ }
+
+ private void OnSettingChanged(bool value)
+ {
+ StartFormat(_inputTextArea.Text);
+ }
+
+ private void OnIndentationModelChanged(Indentation indentationMode)
+ {
+ StartFormat(_inputTextArea.Text);
+ }
+
+ private void OnInputTextChanged(string text)
+ {
+ StartFormat(text);
+ }
+
+ private void StartFormat(string text)
+ {
+ _cancellationTokenSource?.Cancel();
+ _cancellationTokenSource?.Dispose();
+ _cancellationTokenSource = new CancellationTokenSource();
+
+ WorkTask = FormatAsync(text, _cancellationTokenSource.Token, indentationMode, newLineOnAttributes);
+ }
+
+ private async Task FormatAsync(string input, CancellationToken cancellationToken, SettingDefinition<Indentation> indentationSetting, SettingDefinition<bool> newLineOnAttributesetting)
+ {
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ ResultInfo<string> formatResult = XmlHelper.Format(
+ input,
+ _settingsProvider.GetSetting(indentationSetting),
+ _settingsProvider.GetSetting(newLineOnAttributesetting),
+ _logger);
+
+ _outputTextArea.Text(formatResult.Data);
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs
index f31d9e57a..38dacf63d 100644
--- a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs
@@ -204,6 +204,15 @@ namespace DevToys.Tools.Tools.Generators.HashAndChecksum {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input text or an input file.
+ /// </summary>
+ internal static string InvalidInputOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Hash / Checksum Generator.
/// </summary>
diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx
index 887664378..f92bd00ad 100644
--- a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx
+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx
@@ -165,6 +165,9 @@
<data name="InputTextTitle" xml:space="preserve">
<value>Input text</value>
</data>
+ <data name="InvalidInputOrFileCommand" xml:space="preserve">
+ <value>Please specify an input text or an input file</value>
+ </data>
<data name="LongDisplayTitle" xml:space="preserve">
<value>Hash / Checksum Generator</value>
</data>
diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs
index 582435ad7..c0f29020d 100644
--- a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs
@@ -1,5 +1,4 @@
using System.Security.Authentication;
-using DevToys.Api.Core;
using DevToys.Api.Tool.CLI;
using DevToys.Tools.Helpers;
using Microsoft.Extensions.Logging;
@@ -67,7 +66,14 @@ internal sealed class HashAndChecksumGeneratorCommandLineTool : ICommandLineTool
try
{
- using Stream inputStream = await Input.Value.GetStreamAsync(_fileStorage, cancellationToken);
+ ResultInfo<Stream> streamResult = await Input.Value.GetStreamAsync(_fileStorage, cancellationToken);
+ using Stream inputStream = streamResult.Data;
+
+ if (inputStream == null || inputStream == Stream.Null)
+ {
+ Console.Error.WriteLine(HashAndChecksumGenerator.InvalidInputOrFileCommand);
+ return -1;
+ }
string? fileHashString = null;
ConsoleProgressBar? progressBar = Silent ? null : new ConsoleProgressBar();
@@ -87,8 +93,8 @@ internal sealed class HashAndChecksumGeneratorCommandLineTool : ICommandLineTool
if (ChecksumVerification.HasValue)
{
- string? checksum = await ChecksumVerification.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
- if (string.Equals(checksum, fileHashString, StringComparison.OrdinalIgnoreCase))
+ ResultInfo<string> checksum = await ChecksumVerification.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (checksum.HasSucceeded && string.Equals(checksum.Data, fileHashString, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine(HashAndChecksumGenerator.ChecksumVerificationSucceeded);
return 0;
diff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs
index c7c691683..3cb3b6112 100644
--- a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs
@@ -160,7 +160,7 @@ namespace DevToys.Tools.Tools.Graphic.ImageConverter {
}
/// <summary>
- /// Looks up a localized string similar to Directory where the result should be persisted, or a single file path, if the input is also a single file path..
+ /// Looks up a localized string similar to Directory where the result should be saved, or a single file path, if the input is also a single file path..
/// </summary>
internal static string OutputDirectoryOptionDescription {
get {
diff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx
index 92500cd09..07bbdab38 100644
--- a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx
+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx
@@ -152,7 +152,7 @@
<value>Image Converter</value>
</data>
<data name="OutputDirectoryOptionDescription" xml:space="preserve">
- <value>Directory where the result should be persisted, or a single file path, if the input is also a single file path.</value>
+ <value>Directory where the result should be saved, or a single file path, if the input is also a single file path.</value>
</data>
<data name="SaveAll" xml:space="preserve">
<value>Save all</value>
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs
index 8a0eb59e2..a4425e1ab 100644
--- a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs
@@ -240,6 +240,15 @@ namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Input file selected doesn&apos;t exist..
+ /// </summary>
+ internal static string InputFileNotFound {
+ get {
+ return ResourceManager.GetString("InputFileNotFound", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Text or path to a file to treat..
/// </summary>
@@ -249,6 +258,15 @@ namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input text or an input file.
+ /// </summary>
+ internal static string InvalidInputOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to InVeRsE CaSe.
/// </summary>
@@ -295,7 +313,7 @@ namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities {
}
/// <summary>
- /// Looks up a localized string similar to File where the result should be persisted..
+ /// Looks up a localized string similar to Path to the output file.
/// </summary>
internal static string OutputFileOptionDescription {
get {
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx
index 5410adc0a..109d45f13 100644
--- a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx
@@ -177,9 +177,15 @@
<data name="EndOfLineSequenceUnknown" xml:space="preserve">
<value>Unknown</value>
</data>
+ <data name="InputFileNotFound" xml:space="preserve">
+ <value>Input file selected doesn't exist.</value>
+ </data>
<data name="InputOptionDescription" xml:space="preserve">
<value>Text or path to a file to treat.</value>
</data>
+ <data name="InvalidInputOrFileCommand" xml:space="preserve">
+ <value>Please specify an input text or an input file</value>
+ </data>
<data name="InverseCase" xml:space="preserve">
<value>InVeRsE CaSe</value>
</data>
@@ -196,7 +202,7 @@
<value>lower case</value>
</data>
<data name="OutputFileOptionDescription" xml:space="preserve">
- <value>File where the result should be persisted.</value>
+ <value>Path to the output file</value>
</data>
<data name="Paragraphs" xml:space="preserve">
<value>Paragraphs</value>
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs
index dcf5330c7..97a7267ef 100644
--- a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs
@@ -1,5 +1,4 @@
-using DevToys.Api.Core;
-using DevToys.Tools.Helpers;
+using DevToys.Tools.Helpers;
using Microsoft.Extensions.Logging;
using OneOf;
@@ -66,16 +65,22 @@ internal sealed class AnalyzerAndUtilitiesCommandLineTool : ICommandLineTool
public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
{
- string? input = null;
+ if (!Input.HasValue)
+ {
+ Console.Error.WriteLine(AnalyzerAndUtilities.InvalidInputOrFileCommand);
+ return -1;
+ }
- if (Input.HasValue)
+ ResultInfo<string> input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!input.HasSucceeded)
{
- input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ Console.Error.WriteLine(AnalyzerAndUtilities.InputFileNotFound);
+ return -1;
}
- Guard.IsNotNull(input);
+ Guard.IsNotNull(input.Data);
- string newText = input;
+ string newText = input.Data;
for (int i = 0; i < Actions.Length; i++)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -129,15 +134,7 @@ internal sealed class AnalyzerAndUtilitiesCommandLineTool : ICommandLineTool
};
}
- if (OutputFile is null)
- {
- Console.WriteLine(newText);
- }
- else
- {
- await File.WriteAllTextAsync(OutputFile.FullName, newText, cancellationToken);
- }
-
+ await FileHelper.WriteOutputAsync(newText, OutputFile, cancellationToken);
return 0;
}
}
diff --git a/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs b/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs
index 82b4b34b0..5f5c2b49b 100644
--- a/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs
+++ b/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs
@@ -4,24 +4,36 @@ namespace DevToys.UnitTests;
internal sealed class ConsoleOutputMonitor : IDisposable
{
- private readonly StringWriter _stringWriter = new();
+ private readonly StringWriter _outputWriter = new();
+ private readonly StringWriter _errorWriter = new();
private readonly TextWriter _originalOutput = Console.Out;
+ private readonly TextWriter _originalError = Console.Error;
internal ConsoleOutputMonitor()
{
- Console.SetOut(_stringWriter);
+ Console.SetOut(_outputWriter);
+ Console.SetError(_errorWriter);
}
internal string GetOutput()
{
- string result = _stringWriter.ToString();
- _stringWriter.GetStringBuilder().Clear();
+ string result = _outputWriter.ToString();
+ _outputWriter.GetStringBuilder().Clear();
+ return result;
+ }
+
+ internal string GetError()
+ {
+ string result = _errorWriter.ToString();
+ _errorWriter.GetStringBuilder().Clear();
return result;
}
public void Dispose()
{
Console.SetOut(_originalOutput);
- _stringWriter.Dispose();
+ Console.SetError(_originalError);
+ _outputWriter.Dispose();
+ _errorWriter.Dispose();
}
}
diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
index 7164fc580..7cec6444c 100644
--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
@@ -11,6 +11,15 @@
</Content>
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Tools\TestData\XmlFormatter\FourSpaces.xml" />
+ <None Remove="Tools\TestData\XmlFormatter\Minified.xml" />
+ <None Remove="Tools\TestData\XmlFormatter\NewLineOnAttributes.xml" />
+ <None Remove="Tools\TestData\XmlFormatter\OneTab.xml" />
+ <None Remove="Tools\TestData\XmlFormatter\TwoSpaces.xml" />
+ <None Remove="Tools\TestData\XmlFormatter\ValidXml.xml" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="FluentAssertions" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
diff --git a/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs b/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs
index c9769b59f..2c41cccb9 100644
--- a/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs
+++ b/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs
@@ -9,11 +9,13 @@ namespace DevToys.UnitTests.Mocks;
[Export(typeof(IFileStorage))]
internal class MockIFileStorage : IFileStorage
{
+ public bool FileExistsResult { get; set; } = true;
+
public string AppCacheDirectory => throw new NotImplementedException();
public bool FileExists(string relativeOrAbsoluteFilePath)
{
- throw new NotImplementedException();
+ return FileExistsResult;
}
public Stream OpenReadFile(string relativeOrAbsoluteFilePath)
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs
index 8b3619f00..a86cee2c9 100644
--- a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs
+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using DevToys.CLI;
using DevToys.Tools.Models;
using DevToys.Tools.Tools.Converters.JsonYaml;
+using DevToys.UnitTests.Mocks;
using Microsoft.Extensions.Logging;
namespace DevToys.UnitTests.Tools.Converters;
@@ -28,7 +29,6 @@ public sealed class JsonYamlConverterCommandLineToolTests : MefBasedTest
}
[Theory(DisplayName = "Convert with invalid input should return error exit code")]
- [InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task ConvertJsonWithInvalidInputShouldReturnErrorExitCode(string input)
@@ -88,6 +88,7 @@ public sealed class JsonYamlConverterCommandLineToolTests : MefBasedTest
_tool.ConversionMode = JsonToYamlConversion.JsonToYaml;
_tool.Input = inputFile;
_tool.OutputFile = new FileInfo("Dummy.yaml");
+ ((MockIFileStorage)MefProvider.Import<IFileStorage>()).FileExistsResult = false;
int result = await _tool.InvokeAsync(_loggerMock.Object, default);
result.Should().Be(-1);
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterCommandLineToolTests.cs
new file mode 100644
index 000000000..1611e04a0
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterCommandLineToolTests.cs
@@ -0,0 +1,217 @@
+using System.IO;
+using System.Threading.Tasks;
+using DevToys.CLI;
+using DevToys.Tools.Models;
+using DevToys.Tools.Tools.Formatters.Xml;
+using DevToys.UnitTests.Mocks;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.UnitTests.Tools.Formatters;
+
+[Collection(nameof(TestParallelizationDisabled))]
+public sealed class XmlFormatterCommandLineToolTests : MefBasedTest
+{
+ private readonly StringWriter _consoleWriter = new();
+ private readonly StringWriter _consoleErrorWriter = new();
+ private readonly XmlFormatterCommandLineTool _tool;
+ private readonly Mock<ILogger> _loggerMock;
+ private readonly string _baseTestDataDirectory = Path.Combine("Tools", "TestData", nameof(XmlFormatter));
+
+ public XmlFormatterCommandLineToolTests()
+ : base(typeof(XmlFormatterCommandLineTool).Assembly)
+ {
+ _tool = (XmlFormatterCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()
+ .Single(t => t.Metadata.InternalComponentName == "XmlFormatter").Value;
+
+ _loggerMock = new Mock<ILogger>();
+ Console.SetOut(_consoleWriter);
+ Console.SetError(_consoleErrorWriter);
+ }
+
+ [Theory(DisplayName = "Format with invalid input should return error exit code")]
+ [InlineData("")]
+ [InlineData(" ")]
+ public async Task FormatXmlInvalidInputShouldReturnErrorExitCode(string input)
+ {
+ _tool.Input = input;
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(-1);
+ string consoleOutput = _consoleErrorWriter.ToString().Trim();
+ consoleOutput.Should().Be("");
+ }
+
+ [Fact(DisplayName = "Format xml with invalid xml should output invalid xml error")]
+ public async Task FormatXmlInvalidXmlShouldOutputInvalidXmlError()
+ {
+ _tool.Input = "<root><xml></root > ";
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(-1);
+ string consoleOutput = _consoleErrorWriter.ToString().Trim();
+ consoleOutput.Should().Be("The 'xml' start tag on line 1 position 8 does not match the end tag of 'root'. Line 1, position 14.");
+ }
+
+ [Theory(DisplayName = "Format xml with valid xml and two spaces indentation should output valid xml")]
+ [InlineData(true, "<root>\r\n <xml\r\n test=\"true\" />\r\n</root>")]
+ [InlineData(false, "<root>\r\n <xml test=\"true\" />\r\n</root>")]
+ public async Task FormatXmlWithValidXmlAndTwoSpacesShouldOutputValidXml(bool newLineOnAttributes, string expectedResult)
+ {
+ _tool.NewLineOnAttributes = newLineOnAttributes;
+ _tool.Input = "<root><xml test=\"true\" /></root>";
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be(expectedResult);
+ }
+
+ [Theory(DisplayName = "Format xml with valid xml and four spaces indentation should output valid xml")]
+ [InlineData(true, "<root>\r\n <xml\r\n test=\"true\" />\r\n</root>")]
+ [InlineData(false, "<root>\r\n <xml test=\"true\" />\r\n</root>")]
+ public async Task FormatXmlWithValidXmlAndFourSpacesShouldOutputValidXml(bool newLineOnAttributes, string expectedResult)
+ {
+ _tool.IndentationMode = Indentation.FourSpaces;
+ _tool.NewLineOnAttributes = newLineOnAttributes;
+ _tool.Input = "<root><xml test=\"true\" /></root>";
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be(expectedResult);
+ }
+
+ [Theory(DisplayName = "Format xml with valid xml and one tab indentation should output valid xml")]
+ [InlineData(true, "<root>\r\n\t<xml\r\n\t\ttest=\"true\" />\r\n</root>")]
+ [InlineData(false, "<root>\r\n\t<xml test=\"true\" />\r\n</root>")]
+ public async Task FormatXmlWithValidXmlAndOneTabShouldOutputValidXml(bool newLineOnAttributes, string expectedResult)
+ {
+ _tool.IndentationMode = Indentation.OneTab;
+ _tool.NewLineOnAttributes = newLineOnAttributes;
+ _tool.Input = "<root><xml test=\"true\" /></root>";
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be(expectedResult);
+ }
+
+ [Theory(DisplayName = "Format xml with valid xml and minified indentation should output valid xml")]
+ [InlineData(true, "<root><xml test=\"true\" /></root>")]
+ [InlineData(false, "<root><xml test=\"true\" /></root>")]
+ public async Task FormatXmlWithValidXmlAndMinifiedShouldOutputValidXml(bool newLineOnAttributes, string expectedResult)
+ {
+ _tool.IndentationMode = Indentation.Minified;
+ _tool.NewLineOnAttributes = newLineOnAttributes;
+ _tool.Input = "<root><xml test=\"true\" /></root>";
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be(expectedResult);
+ }
+
+ [Fact(DisplayName = "Format xml with unknown xml file should output invalid xml error")]
+ public async Task FormatXmlWithUnknownFileInputShouldReturnErrorExitCode()
+ {
+ string filePath = Path.Combine(_baseTestDataDirectory, "Unknown.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.OutputFile = new FileInfo("Dummy.xml");
+ ((MockIFileStorage)MefProvider.Import<IFileStorage>()).FileExistsResult = false;
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(-1);
+ string consoleOutput = _consoleErrorWriter.ToString().Trim();
+ consoleOutput.Should().Be(XmlFormatter.InputFileNotFound);
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml file and two spaces indentation should output valid xml file")]
+ public async Task FormatXmlWithValidFileInputAndTwoSpacesShouldOutputValidXmlFile()
+ {
+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "TwoSpaces.xml");
+ string expectedContent = File.ReadAllText(expectedFilePath);
+
+ string filePath = Path.Combine(_baseTestDataDirectory, "ValidXml.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.OutputFile = new FileInfo("OutputTwoSpaces.xml");
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);
+ outputContent.Should().Be(expectedContent);
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml file and four spaces indentation should output valid xml file")]
+ public async Task FormatXmlWithValidFileInputAndFourSpacesShouldOutputValidXmlFile()
+ {
+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "FourSpaces.xml");
+ string expectedContent = File.ReadAllText(expectedFilePath);
+
+ string filePath = Path.Combine(_baseTestDataDirectory, "ValidXml.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.IndentationMode = Indentation.FourSpaces;
+ _tool.OutputFile = new FileInfo("OutputFourSpaces.xml");
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);
+ outputContent.Should().Be(expectedContent);
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml file and one tab indentation should output valid xml file")]
+ public async Task FormatXmlWithValidFileInputAndOneTabShouldOutputValidXmlFile()
+ {
+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "OneTab.xml");
+ string expectedContent = File.ReadAllText(expectedFilePath);
+
+ string filePath = Path.Combine(_baseTestDataDirectory, "ValidXml.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.IndentationMode = Indentation.OneTab;
+ _tool.OutputFile = new FileInfo("OutputOneTab.xml");
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);
+ outputContent.Should().Be(expectedContent);
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml file and minified indentation should output valid xml file")]
+ public async Task FormatXmlWithValidFileInputAndMinifiedShouldOutputValidXmlFile()
+ {
+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "Minified.xml");
+ string expectedContent = File.ReadAllText(expectedFilePath);
+
+ string filePath = Path.Combine(_baseTestDataDirectory, "ValidXml.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.IndentationMode = Indentation.Minified;
+ _tool.OutputFile = new FileInfo("OutputMinified.xml");
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);
+ outputContent.Should().Be(expectedContent);
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml file and new line on attributes should output valid xml file")]
+ public async Task FormatXmlWithValidFileInputAndNewLineOnAttributesShouldOutputValidXmlFile()
+ {
+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "NewLineOnAttributes.xml");
+ string expectedContent = File.ReadAllText(expectedFilePath);
+
+ string filePath = Path.Combine(_baseTestDataDirectory, "ValidXml.xml");
+ FileInfo inputFile = TestDataProvider.GetFile(filePath);
+ _tool.Input = inputFile;
+ _tool.NewLineOnAttributes = true;
+ _tool.OutputFile = new FileInfo("OutputNewLineOnAttributes.xml");
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);
+ outputContent.Should().Be(expectedContent);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterGuiToolTests.cs
new file mode 100644
index 000000000..9037911e6
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterGuiToolTests.cs
@@ -0,0 +1,116 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using DevToys.Core.Tools.Metadata;
+using DevToys.Tools.Tools.Formatters.Xml;
+
+namespace DevToys.UnitTests.Tools.Formatters;
+
+public class XmlFormatterGuiToolTests : MefBasedTest
+{
+ private readonly UIToolView _toolView;
+ private readonly XmlFormatterGuiTool _tool;
+ private readonly IUIMultiLineTextInput _inputTextArea;
+ private readonly IUIMultiLineTextInput _outputTextArea;
+
+ public XmlFormatterGuiToolTests()
+ : base(typeof(XmlFormatterGuiTool).Assembly)
+ {
+ _tool = (XmlFormatterGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()
+ .Single(t => t.Metadata.InternalComponentName == "XmlFormatter")
+ .Value;
+
+ _toolView = _tool.View;
+
+ _inputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("xml-input-text-area");
+ _outputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("xml-output-text-area");
+ CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
+ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
+ }
+
+ [Theory(DisplayName = "Format xml with invalid xml should return empty string")]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ public async Task FormatXmlWithInvalidXmlShouldReturnXmlError(string input)
+ {
+ _inputTextArea.Text("abc");
+ _inputTextArea.Text(input);
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("");
+ }
+
+ [Fact(DisplayName = "Format xml with invalid xml should return xml exception message")]
+ public async Task FormatXmlWithInvalidXmlShouldReturnXmlExceptionMessage()
+ {
+ _inputTextArea.Text("<root><xml></root > ");
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("The 'xml' start tag on line 1 position 8 does not match the end tag of 'root'. Line 1, position 14.");
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml and two spaces indentation should return valid xml")]
+ public async Task FormatXmlWithValidXmlAndTwoSpacesShouldReturnValidXml()
+ {
+ _inputTextArea.Text("<root><xml /></root>");
+
+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("xml-text-indentation-setting")).InteractiveElement;
+ indentationOptions.Select(0); // Select TwoSpaces
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root>\r\n <xml />\r\n</root>");
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml and four spaces indentation should return valid xml")]
+ public async Task FormatXmlWithValidXmlAndFourSpacesShouldReturnValidXml()
+ {
+ _inputTextArea.Text("<root><xml /></root>");
+
+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("xml-text-indentation-setting")).InteractiveElement;
+ indentationOptions.Select(1); // Select FourSpaces
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root>\r\n <xml />\r\n</root>");
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml and one tab indentation should return valid xml")]
+ public async Task FormatXmlWithValidXmlAndOneTabShouldReturnValidXml()
+ {
+ _inputTextArea.Text("<root><xml /></root>");
+
+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("xml-text-indentation-setting")).InteractiveElement;
+ indentationOptions.Select(2); // Select OneTab
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root>\r\n\t<xml />\r\n</root>");
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml and minified should return valid xml")]
+ public async Task FormatXmlWithValidXmlAndMinifiedShouldReturnValidXml()
+ {
+ _inputTextArea.Text("<root>\r\n <xml />\r\n</root>");
+
+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("xml-text-indentation-setting")).InteractiveElement;
+ indentationOptions.Select(3); // Select Minified
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root><xml /></root>");
+ }
+
+ [Fact(DisplayName = "Format xml with valid xml and new line on attributes should return valid xml")]
+ public async Task FormatXmlWithValidXmlAndNewLineOnAttributesShouldReturnValidXml()
+ {
+ _inputTextArea.Text("<root><xml test=\"true\" /></root>");
+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("xml-text-indentation-setting")).InteractiveElement;
+ indentationOptions.Select(0); // Select TwoSpaces
+
+ var newLineOnAttributesOptions = (IUISwitch)((IUISetting)_toolView.GetChildElementById("xml-text-newLineOnAttributes-setting")).InteractiveElement;
+ newLineOnAttributesOptions.On();
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root>\r\n <xml\r\n test=\"true\" />\r\n</root>");
+
+ newLineOnAttributesOptions.Off();
+
+ await _tool.WorkTask;
+ _outputTextArea.Text.Should().Be("<root>\r\n <xml test=\"true\" />\r\n</root>");
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs
index 54f5e89b4..cdf7564fb 100644
--- a/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs
+++ b/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs
@@ -48,6 +48,20 @@ public sealed class HashAndChecksumGeneratorCommandLineToolTests : MefBasedTest
result.Should().Be("3e25960a79dbc69b674cd4ec67a72c62");
}
+ [Fact]
+ public async Task HashNonExistentFileOutputsError()
+ {
+ _tool.Input = TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "DoesNotExist.txt"));
+ ((MockIFileStorage)MefProvider.Import<IFileStorage>()).FileExistsResult = false;
+
+ using var consoleOutput = new ConsoleOutputMonitor();
+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);
+ exitCode.Should().Be(-1);
+
+ string result = consoleOutput.GetError().Trim();
+ result.Should().Be(HashAndChecksumGenerator.InvalidInputOrFileCommand);
+ }
+
[Fact]
public async Task HashNoAlgorithm()
{
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs
index 36e98dd4a..d56539f31 100644
--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs
@@ -100,7 +100,7 @@ public class JsonHelperTests
public void ConvertFromYamlShouldReturnEmptyString(string input, string expected)
{
// prepare & act
- ToolResult<string> actual = JsonHelper.ConvertFromYaml(
+ ResultInfo<string> actual = JsonHelper.ConvertFromYaml(
input,
Indentation.FourSpaces,
new MockILogger(),
@@ -117,7 +117,7 @@ public class JsonHelperTests
string expected = string.Empty;
// act
- ToolResult<string> actual = JsonHelper.ConvertFromYaml(
+ ResultInfo<string> actual = JsonHelper.ConvertFromYaml(
input,
Indentation.Minified,
new MockILogger(),
@@ -134,7 +134,7 @@ public class JsonHelperTests
string expected = "While parsing a node, did not find expected node content.";
// act
- ToolResult<string> actual = JsonHelper.ConvertFromYaml(
+ ResultInfo<string> actual = JsonHelper.ConvertFromYaml(
input,
Indentation.Minified,
new MockILogger(),
@@ -148,7 +148,7 @@ public class JsonHelperTests
[InlineData(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]
public void ConvertFromYamlWithTwoSpaces(string input, string expectedResult)
{
- ToolResult<string> result = JsonHelper.ConvertFromYaml(
+ ResultInfo<string> result = JsonHelper.ConvertFromYaml(
input,
Indentation.TwoSpaces,
new MockILogger(),
@@ -161,7 +161,7 @@ public class JsonHelperTests
[InlineData(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]
public void ConvertFromYamlWithFourSpaces(string input, string expectedResult)
{
- ToolResult<string> result = JsonHelper.ConvertFromYaml(
+ ResultInfo<string> result = JsonHelper.ConvertFromYaml(
input,
Indentation.FourSpaces,
new MockILogger(),
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/XmlHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XmlHelperTests.cs
new file mode 100644
index 000000000..b620bde0b
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XmlHelperTests.cs
@@ -0,0 +1,97 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using DevToys.UnitTests.Mocks;
+
+namespace DevToys.UnitTests.Tools.Helpers;
+
+public class XmlHelperTests
+{
+ [Theory]
+ [InlineData(null, false)]
+ [InlineData("", false)]
+ [InlineData(" ", false)]
+ [InlineData("<>", false)]
+ [InlineData("</>", false)]
+ [InlineData("<xml />", true)]
+ [InlineData("<root><xml /></root> ", true)]
+ [InlineData(" <root><xml test=\"true\" /></root>", true)]
+ [InlineData(" <root><xml test=\"true\" /></root ", false)]
+ public void IsValid(string input, bool expectedResult)
+ {
+ XmlHelper.IsValid(input, new MockILogger()).Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData(" ", "")]
+ [InlineData("<xml />", "<xml />")]
+ [InlineData("<root><xml /></root>", "<root>\r\n <xml />\r\n</root>")]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n <xml test=\"true\" />\r\n</root>", false)]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n <xml\r\n test=\"true\" />\r\n</root>", true)]
+ public void FormatTwoSpaces(string input, string expectedResult, bool newLineOnAttributes = false)
+ {
+ ResultInfo<string> actual = XmlHelper.Format(input, Indentation.TwoSpaces, newLineOnAttributes, new MockILogger());
+ actual.Data.Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData(" ", "")]
+ [InlineData("<xml />", "<xml />")]
+ [InlineData("<root><xml /></root>", "<root>\r\n <xml />\r\n</root>")]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n <xml test=\"true\" />\r\n</root>", false)]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n <xml\r\n test=\"true\" />\r\n</root>", true)]
+ public void FormatFourSpaces(string input, string expectedResult, bool newLineOnAttributes = false)
+ {
+ ResultInfo<string> actual = XmlHelper.Format(input, Indentation.FourSpaces, newLineOnAttributes, new MockILogger());
+ actual.Data.Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData(" ", "")]
+ [InlineData("<xml />", "<xml />")]
+ [InlineData("<root><xml /></root>", "<root>\r\n\t<xml />\r\n</root>")]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n\t<xml test=\"true\" />\r\n</root>", false)]
+ [InlineData("<root><xml test=\"true\" /></root>", "<root>\r\n\t<xml\r\n\t\ttest=\"true\" />\r\n</root>", true)]
+ public void FormatOneTab(string input, string expectedResult, bool newLineOnAttributes = false)
+ {
+ ResultInfo<string> actual = XmlHelper.Format(input, Indentation.OneTab, newLineOnAttributes, new MockILogger());
+ actual.Data.Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData(" ", "")]
+ [InlineData("<xml />", "<xml />")]
+ [InlineData("<root>\r\n <xml />\r\n</root>", "<root><xml /></root>")]
+ [InlineData("<root>\r\n <xml />\r\n</root>", "<root><xml /></root>")]
+ [InlineData("<root>\r\n <xml test=\"true\" />\r\n</root>", "<root><xml test=\"true\" /></root>", false)]
+ [InlineData("<root>\r\n <xml\r\n test=\"true\" />\r\n</root>", "<root><xml test=\"true\" /></root>", true)]
+ [InlineData("<root>\r\n\t<xml />\r\n</root>", "<root><xml /></root>")]
+ [InlineData("<root>\r\n\t<xml test=\"true\" />\r\n</root>", "<root><xml test=\"true\" /></root>", false)]
+ [InlineData("<root>\r\n\t<xml\r\n\t\ttest=\"true\" />\r\n</root>", "<root><xml test=\"true\" /></root>", true)]
+ public void FormatMinified(string input, string expectedResult, bool newLineOnAttributes = false)
+ {
+ ResultInfo<string> actual = XmlHelper.Format(input, Indentation.Minified, newLineOnAttributes, new MockILogger());
+ actual.Data.Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData("<?xml version=\"1.0\" ?><Document version=\"0.1\"><Element /></Document>", "<?xml version=\"1.0\" ?><Document version=\"0.1\"><Element /></Document>")]
+ [InlineData("<?xml version=\"1.0\" encoding=\"utf-8\"?><Document version=\"0.1\"><Element /></Document>", "<?xml version=\"1.0\" encoding=\"utf-8\"?><Document version=\"0.1\"><Element /></Document>")]
+ [InlineData("<?xml version=\"1.0\" encoding=\"utf-16\"?><Document version=\"0.1\"><Element /></Document>", "<?xml version=\"1.0\" encoding=\"utf-16\"?><Document version=\"0.1\"><Element /></Document>")]
+ [InlineData("<?xml version=\"1.0\" encoding=\"test\"?><Document version=\"0.1\"><Element /></Document>", "<?xml version=\"1.0\" encoding=\"test\"?><Document version=\"0.1\"><Element /></Document>")]
+ [InlineData("<Document version=\"0.1\"><Element /></Document>", "<Document version=\"0.1\"><Element /></Document>")]
+ public void CheckEncoding(string input, string expectedResult, bool newLineOnAttributes = false)
+ {
+ ResultInfo<string> actual = XmlHelper.Format(input, Indentation.Minified, newLineOnAttributes, new MockILogger());
+ actual.Data.Should().Be(expectedResult);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs
index 45519d8ff..daaa7a12d 100644
--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs
@@ -25,7 +25,7 @@ public class YamlHelperTests
public void ConvertFromJsonShouldReturnEmptyString(string input, string expected)
{
// prepare & act
- ToolResult<string> actual = YamlHelper.ConvertFromJson(
+ ResultInfo<string> actual = YamlHelper.ConvertFromJson(
input,
Indentation.FourSpaces,
new MockILogger(),
@@ -43,7 +43,7 @@ public class YamlHelperTests
string expected = string.Empty;
// act
- ToolResult<string> actual = YamlHelper.ConvertFromJson(
+ ResultInfo<string> actual = YamlHelper.ConvertFromJson(
input,
Indentation.Minified,
new MockILogger(),
@@ -61,7 +61,7 @@ public class YamlHelperTests
string expected = "Expected a digit ('0'-'9'), but instead reached end of data. LineNumber: 0 | BytePositionInLine: 1.";
// act
- ToolResult<string> actual = YamlHelper.ConvertFromJson(
+ ResultInfo<string> actual = YamlHelper.ConvertFromJson(
input,
Indentation.Minified,
new MockILogger(),
@@ -76,7 +76,7 @@ public class YamlHelperTests
[InlineData("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]
public void ConvertFromJsonWithTwoSpaces(string input, string expectedResult)
{
- ToolResult<string> result = YamlHelper.ConvertFromJson(
+ ResultInfo<string> result = YamlHelper.ConvertFromJson(
input,
Indentation.TwoSpaces,
new MockILogger(),
@@ -89,7 +89,7 @@ public class YamlHelperTests
[InlineData("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]
public void ConvertFromJsonWithFourSpaces(string input, string expectedResult)
{
- ToolResult<string> result = YamlHelper.ConvertFromJson(
+ ResultInfo<string> result = YamlHelper.ConvertFromJson(
input,
Indentation.FourSpaces,
new MockILogger(),
@@ -102,7 +102,7 @@ public class YamlHelperTests
[InlineData("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]
public void ConvertFromJsonWithJsonRootArrayWithTwoSpaces(string input, string expectedResult)
{
- ToolResult<string> result = YamlHelper.ConvertFromJson(
+ ResultInfo<string> result = YamlHelper.ConvertFromJson(
input,
Indentation.TwoSpaces,
new MockILogger(),
@@ -115,7 +115,7 @@ public class YamlHelperTests
[InlineData("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]
public void ConvertFromJsonWithJsonRootArrayWithFourSpaces(string input, string expectedResult)
{
- ToolResult<string> result = YamlHelper.ConvertFromJson(
+ ResultInfo<string> result = YamlHelper.ConvertFromJson(
input,
Indentation.FourSpaces,
new MockILogger(),
diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs
new file mode 100644
index 000000000..df3b7e6ae
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs
@@ -0,0 +1,32 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Threading.Tasks;
+using DevToys.Tools.SmartDetection;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.UnitTests.Tools.SmartDetection;
+
+[ExcludeFromCodeCoverage]
+public class XmlDataTypeDetectorTests
+{
+ [Theory]
+ [InlineData(null, false)]
+ [InlineData("", false)]
+ [InlineData(" ", false)]
+ [InlineData("<xml />", true)]
+ [InlineData("<root><xml /></root>", true)]
+ [InlineData("<root><xml test=\"true\" /></root>", true)]
+ [InlineData(" <root>\r\n\t<xml test=\"true\" />\r\n</root>", true)]
+ public async Task TryDetectDataAsync(string input, bool expectedResult)
+ {
+ LoggingExtensions.LoggerFactory ??= LoggerFactory.Create(builder => { });
+
+ DataDetectionResult dataDetectionResult = new(false, input);
+ XmlDataTypeDetector sut = new();
+ DataDetectionResult result = await sut.TryDetectDataAsync(
+ input,
+ dataDetectionResult,
+ default);
+
+ result.Success.Should().Be(expectedResult);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/FourSpaces.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/FourSpaces.xml
new file mode 100644
index 000000000..151a81f91
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/FourSpaces.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/Minified.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/Minified.xml
new file mode 100644
index 000000000..cb2e95959
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/Minified.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="utf-8"?><bookstore xmlns="http://www.contoso.com/books"><book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0"><title>The Autobiography of Benjamin Franklin</title><author><first-name>Benjamin</first-name><last-name>Franklin</last-name></author><price>8.99</price></book><book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2"><title>The Confidence Man</title><author><first-name>Herman</first-name><last-name>Melville</last-name></author><price>11.99</price></book><book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6"><title>The Gorgias</title><author><name>Plato</name></author><price>9.99</price></book></bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/NewLineOnAttributes.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/NewLineOnAttributes.xml
new file mode 100644
index 000000000..b2f91fe7b
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/NewLineOnAttributes.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<bookstore
+ xmlns="http://www.contoso.com/books">
+ <book
+ genre="autobiography"
+ publicationdate="1981-03-22"
+ ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book
+ genre="novel"
+ publicationdate="1967-11-17"
+ ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book
+ genre="philosophy"
+ publicationdate="1991-02-15"
+ ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/OneTab.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/OneTab.xml
new file mode 100644
index 000000000..16650000c
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/OneTab.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/TwoSpaces.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/TwoSpaces.xml
new file mode 100644
index 000000000..b4bf0e58b
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/TwoSpaces.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/ValidXml.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/ValidXml.xml
new file mode 100644
index 000000000..c33dd4dec
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlFormatter/ValidXml.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file