Skip to content

Commit

Permalink
Replace local throw-helpers with ThrowGuard package.
Browse files Browse the repository at this point in the history
  • Loading branch information
ZarehD committed Nov 24, 2023
1 parent b0dcb09 commit b936d8b
Show file tree
Hide file tree
Showing 15 changed files with 79 additions and 95 deletions.
3 changes: 2 additions & 1 deletion src/AspNetStatic/AspNetStatic.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
<Copyright>Copyright 2023 Zareh DerGevorkian. All rights reserved</Copyright>
<Product>AspNetStatic</Product>
<Description>Transforms ASP.NET Core into a static site generator.</Description>
<Version>0.18.0</Version>
<Version>0.18.2</Version>
</PropertyGroup>

<ItemGroup>
Expand All @@ -37,6 +37,7 @@
<ItemGroup>
<PackageReference Include="TestableIO.System.IO.Abstractions" Version="19.2.87" />
<PackageReference Include="TestableIO.System.IO.Abstractions.Wrappers" Version="19.2.87" />
<PackageReference Include="ThrowGuard" Version="1.0.0" />
<PackageReference Include="WebMarkupMin.Core" Version="2.14.0" />
</ItemGroup>

Expand Down
37 changes: 14 additions & 23 deletions src/AspNetStatic/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public static string ToDefaultFileFallback(
this string route, string[] exclusions,
string defaultFileName, string pageFileExtension)
{
Throw.IfNullOrWhiteSpace(route, nameof(route), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhiteSpace(defaultFileName, nameof(defaultFileName), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhiteSpace(pageFileExtension, nameof(pageFileExtension), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(route);
Throw.IfNullOrWhitespace(defaultFileName);
Throw.IfNullOrWhitespace(pageFileExtension);

return
((exclusions is null) || !exclusions.Any(
Expand All @@ -41,10 +41,8 @@ public static string GetOutFilePathname(
string pageFileExtension,
string[] exclusions)
{
Throw.IfNull(page, nameof(page));
Throw.IfNullOrWhiteSpace(
rootFolder, nameof(rootFolder),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNull(page);
Throw.IfNullOrWhitespace(rootFolder);

var pagePath = string.Empty;

Expand All @@ -54,23 +52,18 @@ public static string GetOutFilePathname(
}
else
{
Throw.IfNullOrWhiteSpace(
indexFileName, nameof(indexFileName),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);

Throw.IfNullOrWhiteSpace(
pageFileExtension, nameof(pageFileExtension),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(indexFileName);
Throw.IfNullOrWhitespace(pageFileExtension);

exclusions ??= Array.Empty<string>();

var pageRoute = page.Route.StripQueryString();
var uriKind = UriKind.Relative;

if (!Uri.IsWellFormedUriString(pageRoute, uriKind))
{
Throw.InvalidOp(Properties.Resources.Err_RouteForPageNotWellFormed, uriKind.ToString());
}
Throw.InvalidOpWhen(
() => !Uri.IsWellFormedUriString(pageRoute, uriKind),
SR.Err_RouteForPageNotWellFormed.SF(uriKind.ToString()));

pagePath = pageRoute;

if (pagePath.EndsWith(Consts.FwdSlash) || pagePath.EndsWith(Consts.BakSlash))
Expand Down Expand Up @@ -104,9 +97,7 @@ public static string ToFileSysPath(this string path) =>

public static string StripQueryString(this string url)
{
//Throw.IfNullOrWhiteSpace(
// url, nameof(url),
// Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
//Throw.IfNullOrWhitespace(url);

if (string.IsNullOrWhiteSpace(url)) return url;

Expand All @@ -123,8 +114,8 @@ public static string FixupHrefValues(
bool alwaysDefaultFile = default,
bool routesAreCaseSensitive = default)
{
Throw.IfNull(htmlContent, nameof(htmlContent));
Throw.IfNull(pages, nameof(pages));
Throw.IfNull(htmlContent);
Throw.IfNull(pages);

if (string.IsNullOrWhiteSpace(htmlContent)) return htmlContent;
if (!pages.Any()) return htmlContent;
Expand Down
6 changes: 1 addition & 5 deletions src/AspNetStatic/PageInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,7 @@ public class PageInfo

public PageInfo(string route)
{
Throw.IfNullOrWhiteSpace(
route, nameof(route),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);

this.Route = route;
this.Route = Throw.IfNullOrWhitespace(route);
}
}

Expand Down
9 changes: 4 additions & 5 deletions src/AspNetStatic/StaticPageFallbackMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ the specific language governing permissions and limitations under the License.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;

namespace AspNetStatic
{
Expand Down Expand Up @@ -45,10 +44,10 @@ public StaticPageFallbackMiddleware(
{
this._logger = logger;

this._fileSystem = Throw.IfNull(fileSystem, nameof(fileSystem));
this._next = Throw.IfNull(next, nameof(next));
this._pageInfoProvider = Throw.IfNull(pageInfoProvider, nameof(pageInfoProvider));
Throw.IfNull(environment, nameof(environment));
this._fileSystem = Throw.IfNull(fileSystem);
this._next = Throw.IfNull(next);
this._pageInfoProvider = Throw.IfNull(pageInfoProvider);
Throw.IfNull(environment);
var options = optionsAccessor?.Value ?? new StaticPageFallbackMiddlewareOptions();

this._haveStaticPages = this._pageInfoProvider.Pages.Any();
Expand Down
26 changes: 10 additions & 16 deletions src/AspNetStatic/StaticPageGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@ public static async Task Execute(
var optimizeOutput = config.OptimizePageContent;
var optimizerSelector = config.OptimizerSelector;

if (optimizeOutput && (optimizerSelector is null))
{
Throw.InvalidOp(Properties.Resources.Err_OptimizeWithoutChooser);
}
Throw.InvalidOpWhen(
() => optimizeOutput && (optimizerSelector is null),
SR.Err_OptimizeWithoutChooser);

var destRoot = config.DestinationRoot;
var alwaysDefaultFile = config.AlwaysCreateDefaultFile;
Expand Down Expand Up @@ -160,10 +159,9 @@ public static async Task ExecuteForPage(
var optimizeOutput = config.OptimizePageContent;
var optimizerSelector = config.OptimizerSelector;

if (optimizeOutput && (optimizerSelector is null))
{
Throw.InvalidOp(Properties.Resources.Err_OptimizeWithoutChooser);
}
Throw.InvalidOpWhen(
() => optimizeOutput && (optimizerSelector is null),
SR.Err_OptimizeWithoutChooser);

var destRoot = config.DestinationRoot;
var alwaysDefaultFile = config.AlwaysCreateDefaultFile;
Expand Down Expand Up @@ -257,10 +255,8 @@ await fileSystem.File

private static void RemoveIfExists(IFileSystem fs, string pageDiskPath)
{
Throw.IfNull(fs, nameof(fs));
Throw.IfNullOrWhiteSpace(
pageDiskPath, nameof(pageDiskPath),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNull(fs);
Throw.IfNullOrWhitespace(pageDiskPath);

if (fs.File.Exists(pageDiskPath))
{
Expand All @@ -270,10 +266,8 @@ private static void RemoveIfExists(IFileSystem fs, string pageDiskPath)

private static bool EnsureFolderExists(IFileSystem fs, string pageDiskPath)
{
Throw.IfNull(fs, nameof(fs));
Throw.IfNullOrWhiteSpace(
pageDiskPath, nameof(pageDiskPath),
Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNull(fs);
Throw.IfNullOrWhitespace(pageDiskPath);

var folder = fs.Directory.GetParent(pageDiskPath);

Expand Down
8 changes: 4 additions & 4 deletions src/AspNetStatic/StaticPageGeneratorConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public StaticPageGeneratorConfig(
bool enableOptimization,
IOptimizerSelector? optimizerSelector = default)
{
this.DestinationRoot = Throw.IfNullOrWhiteSpace(destinationRoot, nameof(destinationRoot), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
this.DestinationRoot = Throw.IfNullOrWhitespace(destinationRoot);
this.AlwaysCreateDefaultFile = createDefaultFile;
this.UpdateLinks = fixupHrefValues;

Expand All @@ -53,7 +53,7 @@ public StaticPageGeneratorConfig(
}

this.OptimizePageContent = enableOptimization;
this.OptimizerSelector = Throw.IfNull(this.OptimizePageContent, optimizerSelector);
this.OptimizerSelector = Throw.IfNull(optimizerSelector, () => this.OptimizePageContent);
}

public StaticPageGeneratorConfig(
Expand All @@ -69,8 +69,8 @@ public StaticPageGeneratorConfig(
: this(pages, destinationRoot, createDefaultFile, fixupHrefValues,
enableOptimization, optimizerSelector)
{
this.DefaultFileName = Throw.IfNullOrWhiteSpace(defaultFileName, nameof(defaultFileName), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
this.PageFileExtension = Throw.IfNullOrWhiteSpace(fileExtension, nameof(fileExtension), Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
this.DefaultFileName = Throw.IfNullOrWhitespace(defaultFileName);
this.PageFileExtension = Throw.IfNullOrWhitespace(fileExtension);

if ((defaultFileExclusions is not null) && defaultFileExclusions.Any())
{
Expand Down
43 changes: 23 additions & 20 deletions src/AspNetStatic/StaticPageGeneratorHostExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,13 @@ public static void GenerateStaticPages(
ulong httpTimeoutSeconds = c_DefaultHttpTimeoutSeconds)
{
Throw.IfNull(host);
Throw.IfNullOrWhiteSpace(destinationRoot, message: Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(destinationRoot);

var fileSystem = host.Services.GetService<IFileSystem>() ?? new FileSystem();

if (!fileSystem.Directory.Exists(destinationRoot))
{
Throw.InvalidOp(Properties.Resources.Err_InvalidDestinationRoot);
}
Throw.DirectoryNotFoundWhen(
() => !fileSystem.Directory.Exists(destinationRoot),
SR.Err_InvalidDestinationRoot);

var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(nameof(StaticPageGeneratorHostExtension));
Expand Down Expand Up @@ -288,14 +287,13 @@ public static async Task<bool> GenerateStaticPagesNow(
CancellationToken ct = default)
{
Throw.IfNull(host);
Throw.IfNullOrWhiteSpace(destinationRoot, message: Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(destinationRoot);

var fileSystem = host.Services.GetService<IFileSystem>() ?? new FileSystem();

if (!fileSystem.Directory.Exists(destinationRoot))
{
Throw.InvalidOp(Properties.Resources.Err_InvalidDestinationRoot);
}
Throw.DirectoryNotFoundWhen(
() => !fileSystem.Directory.Exists(destinationRoot),
SR.Err_InvalidDestinationRoot);

var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(nameof(StaticPageGeneratorHostExtension));
Expand Down Expand Up @@ -434,7 +432,7 @@ public static async Task<bool> GenerateStaticPage(
CancellationToken ct = default)
{
Throw.IfNull(host);
Throw.IfNullOrWhiteSpace(pageUrl, message: Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(pageUrl);

var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(nameof(StaticPageGeneratorHostExtension));
Expand Down Expand Up @@ -545,14 +543,13 @@ public static async Task<bool> GenerateStaticPage(
{
Throw.IfNull(host);
Throw.IfNull(page);
Throw.IfNullOrWhiteSpace(destinationRoot, message: Properties.Resources.Err_ValueCannotBeNullEmptyWhitespace);
Throw.IfNullOrWhitespace(destinationRoot);

var fileSystem = host.Services.GetService<IFileSystem>() ?? new FileSystem();

if (!fileSystem.Directory.Exists(destinationRoot))
{
Throw.InvalidOp(Properties.Resources.Err_InvalidDestinationRoot);
}
Throw.DirectoryNotFoundWhen(
() => !fileSystem.Directory.Exists(destinationRoot),
SR.Err_InvalidDestinationRoot);

var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(nameof(StaticPageGeneratorHostExtension));
Expand Down Expand Up @@ -594,15 +591,21 @@ private static string GetBaseUri(IHost host)
{
var hostFeatures = host.Services.GetRequiredService<IServer>().Features;
var serverAddresses = hostFeatures.Get<IServerAddressesFeature>();
if (serverAddresses is null) Throw.InvalidOp($"Feature '{typeof(IServerAddressesFeature)}' is not present.");

var hostUrls = serverAddresses.Addresses;
Throw.InvalidOpWhen(
() => serverAddresses is null,
$"Feature '{typeof(IServerAddressesFeature)}' is not present.");

var hostUrls = serverAddresses!.Addresses;
var baseUri =
hostUrls.FirstOrDefault(x => x.StartsWith(Uri.UriSchemeHttps)) ??
hostUrls.FirstOrDefault(x => x.StartsWith(Uri.UriSchemeHttp));
if (baseUri is null) Throw.InvalidOp(Properties.Resources.Err_HostNotHttpService);

return baseUri;
Throw.InvalidOpWhen(
() => baseUri is null,
SR.Err_HostNotHttpService);

return baseUri!;
}

private static HttpClient GetHttpClient(IHost host, string? httpClientName, ulong httpTimeoutSeconds)
Expand Down
2 changes: 1 addition & 1 deletion src/AspNetStatic/StaticPagesInfoProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public StaticPagesInfoProvider(
IEnumerable<string>? dffExclusions = default)
: base()
{
this.pages.AddRange(Throw.IfNull(pages, nameof(pages)));
this.pages.AddRange(Throw.IfNull(pages));

if (defaultFileName is not null) SetDefaultFileName(defaultFileName);
if (defaultFileExtension is not null) SetDefaultFileExtension(defaultFileExtension);
Expand Down
14 changes: 6 additions & 8 deletions src/AspNetStatic/StaticPagesInfoProviderBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,14 @@ public abstract class StaticPagesInfoProviderBase : IStaticPagesInfoProvider



protected virtual void SetDefaultFileName(string name) => this.defaultFileName = Throw.IfNullOrWhiteSpace(name, nameof(name), Properties.Resources.Err_MissingDefaultFileName);
protected virtual void SetDefaultFileExtension(string extension) => this.defaultFileExtension = Throw.IfNullOrWhiteSpace(extension, nameof(extension), Properties.Resources.Err_MissingDefaultFileExtension);
protected virtual void SetDefaultFileName(string name) => this.defaultFileName = Throw.IfNullOrWhitespace(name, SR.Err_MissingDefaultFileName);
protected virtual void SetDefaultFileExtension(string extension) => this.defaultFileExtension = Throw.IfNullOrWhitespace(extension, SR.Err_MissingDefaultFileExtension);
protected virtual void SetDefaultFileExclusions(string[] newExclusions)
{
if (newExclusions.Any(s => string.IsNullOrWhiteSpace(s)))
{
Throw.BadArg(
nameof(newExclusions),
Properties.Resources.Err_ArrayElementNullOrWhitespace);
}
Throw.BadArgWhen(
() => newExclusions.Any(s => string.IsNullOrWhiteSpace(s)),
SR.Err_ArrayElementNullOrWhitespace,
nameof(newExclusions));

this.exclusions.Clear();
this.exclusions.AddRange(newExclusions);
Expand Down
2 changes: 1 addition & 1 deletion src/AspNetStatic/Throw.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ the specific language governing permissions and limitations under the License.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace AspNetStatic
namespace AspNetStatic.OBSOLETE
{
[StackTraceHidden]
internal static class Throw
Expand Down
2 changes: 2 additions & 0 deletions src/AspNetStatic/Usings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ the specific language governing permissions and limitations under the License.
--------------------------------------------------------------------------------------------------------------------------------*/

global using System.Globalization;
global using ThrowGuard;
global using SR = AspNetStatic.Properties.Resources;
6 changes: 3 additions & 3 deletions src/Tests.AspNetStatic/HelpersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ public void Test_ToDefaultFileFallback_BadInputs()
var emptyString = string.Empty;
var whitespace = " ";

Assert.ThrowsException<ArgumentException>(() => nullString!.ToDefaultFileFallback(_exclusions, _indexFileName, _fileExtension));
Assert.ThrowsException<ArgumentNullException>(() => nullString!.ToDefaultFileFallback(_exclusions, _indexFileName, _fileExtension));
Assert.ThrowsException<ArgumentException>(() => emptyString.ToDefaultFileFallback(_exclusions, _indexFileName, _fileExtension));
Assert.ThrowsException<ArgumentException>(() => whitespace.ToDefaultFileFallback(_exclusions, _indexFileName, _fileExtension));

Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, nullString!, _fileExtension));
Assert.ThrowsException<ArgumentNullException>(() => route.ToDefaultFileFallback(_exclusions, nullString!, _fileExtension));
Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, emptyString, _fileExtension));
Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, whitespace, _fileExtension));

Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, _indexFileName, nullString!));
Assert.ThrowsException<ArgumentNullException>(() => route.ToDefaultFileFallback(_exclusions, _indexFileName, nullString!));
Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, _indexFileName, emptyString));
Assert.ThrowsException<ArgumentException>(() => route.ToDefaultFileFallback(_exclusions, _indexFileName, whitespace));
}
Expand Down
6 changes: 3 additions & 3 deletions src/Tests.AspNetStatic/RouteToPathnameTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public void Test_GetPathname_BadInput_RootFolder()
{
var page = new PageInfo("/");

Assert.ThrowsException<ArgumentException>(
Assert.ThrowsException<ArgumentNullException>(
() => page.GetOutFilePathname(
_nullString, false,
_indexFileName, _pageFileExtension,
Expand All @@ -141,7 +141,7 @@ public void Test_GetPathname_BadInput_IndexFileName()
{
var page = new PageInfo("/");

Assert.ThrowsException<ArgumentException>(
Assert.ThrowsException<ArgumentNullException>(
() => page.GetOutFilePathname(
_webroot, false,
_nullString, _pageFileExtension,
Expand All @@ -165,7 +165,7 @@ public void Test_GetPathname_BadInput_PageFileExtension()
{
var page = new PageInfo("/");

Assert.ThrowsException<ArgumentException>(
Assert.ThrowsException<ArgumentNullException>(
() => page.GetOutFilePathname(
_webroot, false,
_indexFileName, _nullString,
Expand Down
Loading

0 comments on commit b936d8b

Please sign in to comment.