Skip to content

Commit

Permalink
Added js minifier
Browse files Browse the repository at this point in the history
  • Loading branch information
TwentyFourMinutes committed Jun 25, 2020
1 parent 5ea9b78 commit 0eeb8aa
Show file tree
Hide file tree
Showing 11 changed files with 446 additions and 114 deletions.
73 changes: 0 additions & 73 deletions src/RazorMinifier/RazorMinifier.Core/Minifier.cs

This file was deleted.

83 changes: 83 additions & 0 deletions src/RazorMinifier/RazorMinifier.Core/Minifiers/CSHtmlMinifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace RazorMinifier.Core.Minifiers
{
public static class CSHtmlMinifier
{
private static readonly Regex _emptyLineRegex;
private static readonly Regex _multiLineCommentRegex;
private static readonly Regex _razorSectionRegex;
private static readonly Regex _razorFunctionsRegex;

static CSHtmlMinifier()
{
_emptyLineRegex = new Regex(@"(^(\s)+|(\s)*(\v|\n|\r))", RegexOptions.Multiline);
_multiLineCommentRegex = new Regex(@"(<!--(.|\n)*?-->|\/\*(.|\n)*?\*\/|@\*(.|\n)*?\*@)");
_razorSectionRegex = new Regex(@"@section\s\w+\s?{");
_razorFunctionsRegex = new Regex(@"@functions\s\w+\s?{");
}

public static void MinifyFile(string source, string output)
{
var content = File.ReadAllText(source);

content = Minify(content);

File.WriteAllText(output, content);
}

public static string Minify(string input)
{
var headers = new List<string>();

while (true)
{
if (input.StartsWith("@"))
{
var index = input.IndexOf(Environment.NewLine);

if (index == -1)
break;

var lastChar = input[index - 1];

if (lastChar == '{' || lastChar == '}')
break;

var content = input.Substring(0, index);
input = input.Remove(0, index + 2);

headers.Add(content);
}
else
{
break;
}
}

input = _multiLineCommentRegex.Replace(input, string.Empty);

input = _emptyLineRegex.Replace(input, string.Empty);

foreach (Match match in _razorSectionRegex.Matches(input))
{
input = input.Insert(match.Index, Environment.NewLine);
}

foreach (Match match in _razorFunctionsRegex.Matches(input))
{
input = input.Insert(match.Index, Environment.NewLine);
}

foreach (var header in headers)
{
input = string.Concat(header, Environment.NewLine, input);
}

return input;
}
}
}
83 changes: 83 additions & 0 deletions src/RazorMinifier/RazorMinifier.Core/Minifiers/JsMinifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using StringyEnums;

namespace RazorMinifier.Core.Minifiers
{
public static class JsMinifier
{
static JsMinifier()
{
EnumCore.Init(cache => cache.InitWith<Options>(), false);
}

[Flags]
public enum Options
{
None = 0,
[StringRepresentation("--minify-whitespace")]
RemoveWhitespaces = 1,
[StringRepresentation("--minify-identifiers")]
ShortenIdentifiers = 2,
[StringRepresentation("--minify-syntax")]
ShortenSyntax = 4,
All = RemoveWhitespaces | ShortenIdentifiers | ShortenSyntax
}

public static async Task<bool> TryMinifyFileAsync(string esbuildPath, string source, string output, Options options = Options.All)
{
var arguments = ComposeArguments(source, output, options);

var proccessStartInfo = new ProcessStartInfo
{
WorkingDirectory = Directory.GetCurrentDirectory(),
Arguments = arguments,
CreateNoWindow = true,
FileName = esbuildPath,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardError = true,
UseShellExecute = false
};

var process = new Process
{
StartInfo = proccessStartInfo
};

await process.StartAndWaitForExitAsync(false);

var processOutputError = await process.StandardError.ReadToEndAsync();

process.Dispose();

if (!string.IsNullOrWhiteSpace(processOutputError))
{
return false;
}

return true;
}

private static string ComposeArguments(string source, string output, Options options = Options.All)
{
var argumentsBuilder = new StringBuilder();

argumentsBuilder.Append(source);

foreach (var stringOption in options.GetFlagRepresentation())
{
argumentsBuilder.Append(' ');
argumentsBuilder.Append(stringOption);
}

argumentsBuilder.Append(" --outfile=");

argumentsBuilder.Append(output);

return argumentsBuilder.ToString();
}
}
}
47 changes: 47 additions & 0 deletions src/RazorMinifier/RazorMinifier.Core/ProccessExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace RazorMinifier.Core
{
public static class ProcessExtensions
{
public static async Task StartAndWaitForExitAsync(this Process process, bool dispose = true, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();

void Process_Exited(object sender, EventArgs e)
{
tcs.TrySetResult(true);
}

process.EnableRaisingEvents = true;
process.Exited += Process_Exited;

process.Start();

try
{
if (process.HasExited)
{
return;
}

using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
await tcs.Task;
}
}
finally
{
process.Exited -= Process_Exited;

if (dispose)
{
process.Dispose();
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="StringyEnums" Version="1.2.0" />
</ItemGroup>

</Project>
Loading

0 comments on commit 0eeb8aa

Please sign in to comment.