Skip to content

Commit 34a5af1

Browse files
authored
Fixed bugs, Cleaned and Improved exception throwing (#1)
* Fixed bugs, Cleaned and Improved exception throwing * changed PackageReference to 1.0.0-preview2
1 parent 7f8d87d commit 34a5af1

File tree

6 files changed

+65
-43
lines changed

6 files changed

+65
-43
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
[![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)
66

7-
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.
7+
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.
88

99
```json
1010
{

src/CompactJson/CompactJsonTask.cs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using Microsoft.Build.Framework;
45
using Microsoft.Build.Utilities;
6+
using static Microsoft.Build.Framework.MessageImportance;
57

68
namespace MSBuild.CompactJsonResources
79
{
@@ -19,42 +21,38 @@ public class CompactJsonTask : Task
1921

2022
public override bool Execute()
2123
{
22-
LogMessage($"{nameof(TempOutputPath)}: {TempOutputPath}");
24+
LogMessage($"{nameof(TempOutputPath)}: {TempOutputPath}", High);
2325
try
2426
{
2527
if (JsonFiles?.Length > 0)
2628
OutputJsonFiles = ParseAndCopyFiles(JsonFiles)?.ToArray();
2729
else
28-
Log.LogMessage($"{nameof(JsonFiles)} is null or empty");
30+
LogMessage($"{nameof(JsonFiles)} is null or empty");
2931

3032
}
3133
catch (Exception ex)
3234
{
33-
LogMessage(ex.StackTrace);
34-
Log.LogErrorFromException(ex);
35+
Log.LogErrorFromException(ex, true);
3536
return false;
3637
}
3738

3839
return true;
3940
}
4041

41-
42-
List<ITaskItem> ParseAndCopyFiles(ITaskItem[] items)
42+
IEnumerable<ITaskItem> ParseAndCopyFiles(ITaskItem[] items)
4343
{
44-
var output = new List<ITaskItem>();
4544
foreach(var item in items)
4645
{
47-
LogMessage(item.ToString("Original File"));
46+
LogMessage(item.ToString("Original File"), Low);
4847
var json = new JsonFile(item, TempOutputPath);
4948
LogMessage($"Temp File Full Path: {json.TempFullPath}");
5049
var outputItem = json.WriteCompactTempFile();
51-
LogMessage(outputItem.ToString("Temp File"));
52-
output.Add(outputItem);
50+
LogMessage(outputItem.ToString("Temp File"), Low);
51+
yield return outputItem;
5352
}
54-
return output;
5553
}
56-
5754

58-
void LogMessage(string mess) => Log.LogMessage($"{LogTag}{mess}");
55+
void LogMessage(string mess, MessageImportance importance = Normal)
56+
=> Log.LogMessage(importance, $"{LogTag}{mess}");
5957
}
6058
}

src/CompactJson/Extension.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,8 @@ public static string ToString(this ITaskItem item, string title)
1717

1818
return result;
1919
}
20+
21+
public static bool IsEmpty(this string value)
22+
=> string.IsNullOrWhiteSpace(value);
2023
}
2124
}

src/CompactJson/JsonFile.cs

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public class JsonFile
1212
const string definingProjectFullPath = "DefiningProjectFullPath";
1313
const string definingProjectName = "DefiningProjectName";
1414
const string definingProjectExtension = "DefiningProjectExtension";
15+
const char dotChar = '.';
1516

1617
readonly ITaskItem item;
1718
readonly string tempOutputPath;
@@ -53,34 +54,36 @@ public JsonFile(string link, string filename, string extension, string fullPath,
5354

5455
public TaskItem WriteCompactTempFile()
5556
{
56-
using var fs = File.OpenRead(FullPath);
57-
using var jDoc = JsonDocument.Parse(fs, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
57+
using var frs = File.OpenRead(FullPath);
58+
using var jDoc = JsonDocument.Parse(frs,
59+
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
5860

5961
var directory = Path.GetDirectoryName(TempFullPath);
62+
6063
if (!Directory.Exists(directory))
6164
Directory.CreateDirectory(directory);
6265

6366
if (File.Exists(TempFullPath))
6467
File.Delete(TempFullPath);
6568

66-
using var stream = File.OpenWrite(TempFullPath);
67-
using var writer = new Utf8JsonWriter(stream);
69+
using var fws = File.OpenWrite(TempFullPath);
70+
using var writer = new Utf8JsonWriter(fws);
6871
jDoc.WriteTo(writer);
6972
writer.Flush();
70-
stream.Flush();
73+
fws.Flush();
7174

7275
return GetTaskItem();
7376
}
7477

7578
public override string ToString() => FullPath;
7679

7780
TaskItem GetTaskItem()
78-
=> new TaskItem(TempFullPath, new Dictionary<string, string>
81+
=> new(TempFullPath, new Dictionary<string, string>
7982
{
8083
{ nameof(Link), Link },
8184
{ nameof(FullPath), TempFullPath },
82-
{ nameof(Filename), Filename },
83-
{ nameof(Extension), Extension },
85+
{ nameof(Filename), Path.GetFileNameWithoutExtension(TempFullPath) },
86+
{ nameof(Extension), Path.GetExtension(TempFullPath) },
8487
{ nameof(DefiningProjectDirectory), DefiningProjectDirectory },
8588
{ definingProjectFullPath, GetMetadata(definingProjectFullPath) },
8689
{ definingProjectName, GetMetadata(definingProjectName) },
@@ -91,24 +94,41 @@ TaskItem GetTaskItem()
9194

9295
void Verify()
9396
{
94-
if (string.IsNullOrWhiteSpace(DefiningProjectDirectory) || string.IsNullOrWhiteSpace(FullPath))
95-
throw new Exception();
97+
if (DefiningProjectDirectory.IsEmpty() || FullPath.IsEmpty())
98+
throw new KeyNotFoundException($"{nameof(DefiningProjectDirectory)} or {nameof(FullPath)} not found in {item.ToString(null)}");
99+
100+
if (!File.Exists(FullPath))
101+
throw new FileNotFoundException(FullPath);
102+
103+
if (!Directory.Exists(DefiningProjectDirectory))
104+
throw new DirectoryNotFoundException(DefiningProjectDirectory);
105+
106+
VerifyFileNameWithExtension();
96107

97-
if (string.IsNullOrWhiteSpace(Link))
98-
SetLink();
108+
if (Link.IsEmpty())
109+
Link = FullPath.StartsWith(DefiningProjectDirectory)
110+
? FullPath.Replace(DefiningProjectDirectory, string.Empty)
111+
: $"{Filename}{Extension}";
99112

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

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

106-
void SetLink()
119+
void VerifyFileNameWithExtension()
107120
{
108-
var locatedInProject = FullPath.StartsWith(DefiningProjectDirectory);
109-
Link = locatedInProject
110-
? FullPath.Replace(DefiningProjectDirectory, string.Empty)
111-
: $"{Filename}{Extension}";
121+
if (Filename.IsEmpty())
122+
Filename = Path.GetFileNameWithoutExtension(FullPath);
123+
124+
if (Extension.IsEmpty())
125+
Extension = Path.GetExtension(FullPath);
126+
127+
if (!Extension.IsEmpty() && !Extension.StartsWith(dotChar))
128+
Extension = dotChar + Extension;
129+
130+
if (Filename.IsEmpty() && Extension.IsEmpty())
131+
throw new ArgumentException($"The {nameof(Filename)} and {nameof(Extension)} could not be determined in {item.ToString(null)}");
112132
}
113133
}
114134
}

src/CompactJson/MSBuild.CompactJsonResources.csproj

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,24 @@
55
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
66
<DevelopmentDependency>true</DevelopmentDependency>
77
<IncludeBuildOutput>false</IncludeBuildOutput>
8+
<LangVersion>9</LangVersion>
89
<NoWarn>NU5100;NU5128</NoWarn>
910

1011
<PackageId>MSBuild.CompactJsonResources</PackageId>
1112
<PackageTags>MSBuild, Json</PackageTags>
12-
<Version>1.0.0-preview1</Version>
13+
<Version>1.0.0-preview2</Version>
1314
<Authors>dimonovdd</Authors>
1415
<Owners>dimonovdd</Owners>
15-
<Description>Compact Json data, remove all whitespaces before build</Description>
16+
<Description>Compact Json data by removing whitespaces before building</Description>
1617
<RepositoryUrl>https://github.com/dimonovdd/MSBuild.CompactJsonResources</RepositoryUrl>
1718
<PackageReleaseNotes>See: https://github.com/dimonovdd/MSBuild.CompactJsonResources/releases</PackageReleaseNotes>
1819
<PackageLicenseFile>LICENSE</PackageLicenseFile>
1920
<PackageIcon>icon.png</PackageIcon>
2021
</PropertyGroup>
2122
<ItemGroup>
22-
<PackageReference Include="Microsoft.Build.Framework" Version="16.7.0" PrivateAssets="all" />
23-
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.7.0" PrivateAssets="all" />
24-
<PackageReference Include="System.Text.Json" Version="5.0.2" />
23+
<PackageReference Include="Microsoft.Build.Framework" Version="16.11.0" PrivateAssets="all" />
24+
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.11.0" PrivateAssets="all" />
25+
<PackageReference Include="System.Text.Json" Version="5.0.2" PrivateAssets="all" />
2526
</ItemGroup>
2627
<ItemGroup>
2728
<None Include="..\..\LICENSE" PackagePath="" Pack="true" />

src/TestMSBuildTasks/TestMSBuildTasks.csproj

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<OutputType>Exe</OutputType>
55
<TargetFramework>net5.0</TargetFramework>
66
<UseAppHost>false</UseAppHost>
7-
<EnableCompactJson>true</EnableCompactJson>
7+
<EnableCompactJson>false</EnableCompactJson>
88
</PropertyGroup>
99
<ItemGroup>
1010
<JsonEmbeddedResource Include="inProject.json" />
@@ -13,8 +13,8 @@
1313
<JsonEmbeddedResource Include="..\RelativeResFolder2\*.json" Link="ProjectResFolder\%(Filename)WithLink%(Extension)" />
1414
<JsonEmbeddedResource Include="/Users/dmitriidimov/Documents/projects/TestMSBuildTasks/TestMSBuildTasks/AbsoluteResFolder/absolutePath.json" />
1515
</ItemGroup>
16-
<!--<ItemGroup>
17-
<PackageReference Include="MSBuild.CompactJsonResources" Version="1.0.0-preview1" />
18-
</ItemGroup>-->
19-
<Import Project="..\CompactJson\bin\$(Configuration)\netstandard2.1\MSBuild.CompactJsonResources.targets" />
16+
<ItemGroup>
17+
<PackageReference Include="MSBuild.CompactJsonResources" Version="1.0.0-preview2" PrivateAssets="all"/>
18+
</ItemGroup>
19+
<!--<Import Project="..\CompactJson\bin\$(Configuration)\netstandard2.1\MSBuild.CompactJsonResources.targets" />-->
2020
</Project>

0 commit comments

Comments
 (0)