Skip to content

Commit

Permalink
Reduce contention on destination file
Browse files Browse the repository at this point in the history
  • Loading branch information
mikes-gh committed Dec 31, 2023
1 parent 0e20e6a commit 012b440
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
44 changes: 34 additions & 10 deletions CompileJS.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

Expand All @@ -15,21 +17,43 @@ public class CompileJS : Task

public override bool Execute()
{
File.Delete(DestinationFile);
var sourceDirectory = new DirectoryInfo(SourceDirectory);
var files = sourceDirectory.GetFiles("*.js");
var sourceFiles = new DirectoryInfo(SourceDirectory).GetFiles("*.js");
var maxSourceWriteTime = new DateTime();
bool destinationNeedsUpdate = false;

foreach (var file in files)
foreach (var sourceFile in sourceFiles)
{
var fileText = File.ReadAllText(file.FullName);
File.AppendAllText(DestinationFile, fileText);
maxSourceWriteTime = sourceFile.LastWriteTime > maxSourceWriteTime ? sourceFile.LastWriteTime : maxSourceWriteTime;
}

using (var reader = new StreamReader(DestinationFile))
if (File.Exists(DestinationFile))
{
var writer = new StringWriter();
JavaScriptCompressor.Compress(reader, writer);
File.WriteAllText(DestinationFile, writer.GetStringBuilder().ToString(), reader.CurrentEncoding);
if (File.GetLastWriteTime(DestinationFile) < maxSourceWriteTime)
{
destinationNeedsUpdate = true;
Log.LogMessage(MessageImportance.High, $"{DestinationFile} Updated");
}
else
{
Log.LogMessage(MessageImportance.High, $"{DestinationFile} UpToDate");
}
}
else
{
destinationNeedsUpdate = true;
Log.LogMessage(MessageImportance.High, $"{DestinationFile} Created");
}

if (destinationNeedsUpdate)
{
var combinedJS = new StringBuilder();
foreach (var sourceFile in sourceFiles)
{
var fileText = File.ReadAllText(sourceFile.FullName);
combinedJS.Append(fileText);
}
var compressedJS = JavaScriptCompressor.Compress(combinedJS.ToString());
File.WriteAllText(DestinationFile, compressedJS);
}

GeneratedFile = new TaskItem(DestinationFile);
Expand Down
2 changes: 1 addition & 1 deletion MudBlazor.JSCompiler.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<PackageId>MudBlazor.JSCompiler</PackageId>
<Version>1.0.7</Version>
<Version>1.0.9</Version>
<Authors>mikes-gh</Authors>
<Description>MudBlazor JS Compiler Library</Description>
<PackageDescription>MudBlazor JS Compiler Library</PackageDescription>
Expand Down

0 comments on commit 012b440

Please sign in to comment.