Skip to content

Commit

Permalink
Fixed bugs, Cleaned and Improved exception throwing (#1)
Browse files Browse the repository at this point in the history
* Fixed bugs, Cleaned and Improved exception throwing
* changed PackageReference to 1.0.0-preview2
  • Loading branch information
dimonovdd authored Aug 27, 2021
1 parent 7f8d87d commit 34a5af1
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 43 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

[![NuGet Badge](https://img.shields.io/nuget/vpre/MSBuild.CompactJsonResources)](https://www.nuget.org/packages/MSBuild.CompactJsonResources/) [![license](https://img.shields.io/github/license/dimonovdd/MSBuild.CompactJsonResources)](https://github.com/dimonovdd/MSBuild.CompactJsonResources/blob/main/LICENSE) [![fuget.org](https://www.fuget.org/packages/MSBuild.CompactJsonResources/badge.svg)](https://www.fuget.org/packages/MSBuild.CompactJsonResources)

Often, Json files are added to a project as one line to reduce the size of the build. Such files are uncomfortable to read and track changes through version control systems. This package removes whitespaces, trailing commas and comments from the builds without changing the beautiful Json source files by adding their single-line copies.
Often, Json files are added to a project as one line to reduce the size of the build. Such files are uncomfortable to read and track changes through version control systems. This package resolve this problem by removing whitespaces, trailing commas and comments from the builds without changing the beautiful Json source files by adding their single-line copies.

```json
{
Expand Down
24 changes: 11 additions & 13 deletions src/CompactJson/CompactJsonTask.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using static Microsoft.Build.Framework.MessageImportance;

namespace MSBuild.CompactJsonResources
{
Expand All @@ -19,42 +21,38 @@ public class CompactJsonTask : Task

public override bool Execute()
{
LogMessage($"{nameof(TempOutputPath)}: {TempOutputPath}");
LogMessage($"{nameof(TempOutputPath)}: {TempOutputPath}", High);
try
{
if (JsonFiles?.Length > 0)
OutputJsonFiles = ParseAndCopyFiles(JsonFiles)?.ToArray();
else
Log.LogMessage($"{nameof(JsonFiles)} is null or empty");
LogMessage($"{nameof(JsonFiles)} is null or empty");

}
catch (Exception ex)
{
LogMessage(ex.StackTrace);
Log.LogErrorFromException(ex);
Log.LogErrorFromException(ex, true);
return false;
}

return true;
}


List<ITaskItem> ParseAndCopyFiles(ITaskItem[] items)
IEnumerable<ITaskItem> ParseAndCopyFiles(ITaskItem[] items)
{
var output = new List<ITaskItem>();
foreach(var item in items)
{
LogMessage(item.ToString("Original File"));
LogMessage(item.ToString("Original File"), Low);
var json = new JsonFile(item, TempOutputPath);
LogMessage($"Temp File Full Path: {json.TempFullPath}");
var outputItem = json.WriteCompactTempFile();
LogMessage(outputItem.ToString("Temp File"));
output.Add(outputItem);
LogMessage(outputItem.ToString("Temp File"), Low);
yield return outputItem;
}
return output;
}


void LogMessage(string mess) => Log.LogMessage($"{LogTag}{mess}");
void LogMessage(string mess, MessageImportance importance = Normal)
=> Log.LogMessage(importance, $"{LogTag}{mess}");
}
}
3 changes: 3 additions & 0 deletions src/CompactJson/Extension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,8 @@ public static string ToString(this ITaskItem item, string title)

return result;
}

public static bool IsEmpty(this string value)
=> string.IsNullOrWhiteSpace(value);
}
}
58 changes: 39 additions & 19 deletions src/CompactJson/JsonFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class JsonFile
const string definingProjectFullPath = "DefiningProjectFullPath";
const string definingProjectName = "DefiningProjectName";
const string definingProjectExtension = "DefiningProjectExtension";
const char dotChar = '.';

readonly ITaskItem item;
readonly string tempOutputPath;
Expand Down Expand Up @@ -53,34 +54,36 @@ public JsonFile(string link, string filename, string extension, string fullPath,

public TaskItem WriteCompactTempFile()
{
using var fs = File.OpenRead(FullPath);
using var jDoc = JsonDocument.Parse(fs, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
using var frs = File.OpenRead(FullPath);
using var jDoc = JsonDocument.Parse(frs,
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });

var directory = Path.GetDirectoryName(TempFullPath);

if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);

if (File.Exists(TempFullPath))
File.Delete(TempFullPath);

using var stream = File.OpenWrite(TempFullPath);
using var writer = new Utf8JsonWriter(stream);
using var fws = File.OpenWrite(TempFullPath);
using var writer = new Utf8JsonWriter(fws);
jDoc.WriteTo(writer);
writer.Flush();
stream.Flush();
fws.Flush();

return GetTaskItem();
}

public override string ToString() => FullPath;

TaskItem GetTaskItem()
=> new TaskItem(TempFullPath, new Dictionary<string, string>
=> new(TempFullPath, new Dictionary<string, string>
{
{ nameof(Link), Link },
{ nameof(FullPath), TempFullPath },
{ nameof(Filename), Filename },
{ nameof(Extension), Extension },
{ nameof(Filename), Path.GetFileNameWithoutExtension(TempFullPath) },
{ nameof(Extension), Path.GetExtension(TempFullPath) },
{ nameof(DefiningProjectDirectory), DefiningProjectDirectory },
{ definingProjectFullPath, GetMetadata(definingProjectFullPath) },
{ definingProjectName, GetMetadata(definingProjectName) },
Expand All @@ -91,24 +94,41 @@ TaskItem GetTaskItem()

void Verify()
{
if (string.IsNullOrWhiteSpace(DefiningProjectDirectory) || string.IsNullOrWhiteSpace(FullPath))
throw new Exception();
if (DefiningProjectDirectory.IsEmpty() || FullPath.IsEmpty())
throw new KeyNotFoundException($"{nameof(DefiningProjectDirectory)} or {nameof(FullPath)} not found in {item.ToString(null)}");

if (!File.Exists(FullPath))
throw new FileNotFoundException(FullPath);

if (!Directory.Exists(DefiningProjectDirectory))
throw new DirectoryNotFoundException(DefiningProjectDirectory);

VerifyFileNameWithExtension();

if (string.IsNullOrWhiteSpace(Link))
SetLink();
if (Link.IsEmpty())
Link = FullPath.StartsWith(DefiningProjectDirectory)
? FullPath.Replace(DefiningProjectDirectory, string.Empty)
: $"{Filename}{Extension}";

if (string.IsNullOrWhiteSpace(Link))
throw new Exception();
if (Link.IsEmpty())
throw new ArgumentException($"The relative {nameof(Link)} of the file location in the project could not be determined in {item.ToString(null)}");

TempFullPath = Path.Combine(tempOutputPath, Link);
}

void SetLink()
void VerifyFileNameWithExtension()
{
var locatedInProject = FullPath.StartsWith(DefiningProjectDirectory);
Link = locatedInProject
? FullPath.Replace(DefiningProjectDirectory, string.Empty)
: $"{Filename}{Extension}";
if (Filename.IsEmpty())
Filename = Path.GetFileNameWithoutExtension(FullPath);

if (Extension.IsEmpty())
Extension = Path.GetExtension(FullPath);

if (!Extension.IsEmpty() && !Extension.StartsWith(dotChar))
Extension = dotChar + Extension;

if (Filename.IsEmpty() && Extension.IsEmpty())
throw new ArgumentException($"The {nameof(Filename)} and {nameof(Extension)} could not be determined in {item.ToString(null)}");
}
}
}
11 changes: 6 additions & 5 deletions src/CompactJson/MSBuild.CompactJsonResources.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,24 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<DevelopmentDependency>true</DevelopmentDependency>
<IncludeBuildOutput>false</IncludeBuildOutput>
<LangVersion>9</LangVersion>
<NoWarn>NU5100;NU5128</NoWarn>

<PackageId>MSBuild.CompactJsonResources</PackageId>
<PackageTags>MSBuild, Json</PackageTags>
<Version>1.0.0-preview1</Version>
<Version>1.0.0-preview2</Version>
<Authors>dimonovdd</Authors>
<Owners>dimonovdd</Owners>
<Description>Compact Json data, remove all whitespaces before build</Description>
<Description>Compact Json data by removing whitespaces before building</Description>
<RepositoryUrl>https://github.com/dimonovdd/MSBuild.CompactJsonResources</RepositoryUrl>
<PackageReleaseNotes>See: https://github.com/dimonovdd/MSBuild.CompactJsonResources/releases</PackageReleaseNotes>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageIcon>icon.png</PackageIcon>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Framework" Version="16.7.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.7.0" PrivateAssets="all" />
<PackageReference Include="System.Text.Json" Version="5.0.2" />
<PackageReference Include="Microsoft.Build.Framework" Version="16.11.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.11.0" PrivateAssets="all" />
<PackageReference Include="System.Text.Json" Version="5.0.2" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE" PackagePath="" Pack="true" />
Expand Down
10 changes: 5 additions & 5 deletions src/TestMSBuildTasks/TestMSBuildTasks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<UseAppHost>false</UseAppHost>
<EnableCompactJson>true</EnableCompactJson>
<EnableCompactJson>false</EnableCompactJson>
</PropertyGroup>
<ItemGroup>
<JsonEmbeddedResource Include="inProject.json" />
Expand All @@ -13,8 +13,8 @@
<JsonEmbeddedResource Include="..\RelativeResFolder2\*.json" Link="ProjectResFolder\%(Filename)WithLink%(Extension)" />
<JsonEmbeddedResource Include="/Users/dmitriidimov/Documents/projects/TestMSBuildTasks/TestMSBuildTasks/AbsoluteResFolder/absolutePath.json" />
</ItemGroup>
<!--<ItemGroup>
<PackageReference Include="MSBuild.CompactJsonResources" Version="1.0.0-preview1" />
</ItemGroup>-->
<Import Project="..\CompactJson\bin\$(Configuration)\netstandard2.1\MSBuild.CompactJsonResources.targets" />
<ItemGroup>
<PackageReference Include="MSBuild.CompactJsonResources" Version="1.0.0-preview2" PrivateAssets="all"/>
</ItemGroup>
<!--<Import Project="..\CompactJson\bin\$(Configuration)\netstandard2.1\MSBuild.CompactJsonResources.targets" />-->
</Project>

0 comments on commit 34a5af1

Please sign in to comment.